How to make a field in django model that is either a value or a foreign key?

Viewed 236

I don't know if that is possible, maybe I have to come up with a particular design but I am struggling with the following:

These are my models


class Rectangle(models.Model):
    height = models.CharField(max_length=255)
    width = models.CharField(max_length=255)

class Variable(models.Model):
    name = models.CharField(max_length=255)
    value = models.CharField(max_length=255)

I would like the width and the height to be either a value, or a variable that has the value. For instance, if the user nputs a height that starts with a special character, say "@variablename" it should be able to find and reference the variable, otherwise just save the value if the input was "350" for instance.

Can anyone help me? Thanks in advance

1 Answers

You can set a relation with Vairable model for height and width fields.

class Rectangle(models.Model):
    height = models.Foreignkey(Variable,on_delete=#SET_NULL,CASCADE vs what you want)
    width = models.Foreignkey(Variable,on_delete=#SET_NULL,CASCADE vs what you want)

If user give a special value name you can find and connect your field with Variable object. Other ones, if the user give only value, you can create any Variable object and connect it to related field.

Related