user9317843
user9317843

Reputation:

How to add a conditional field in a Django model?

Basically, what I want is a field to be available if a condition is met, so something like this:

class ConditionalModel(models.Model):
    product = models.ForeignKey(product, on_delete=models.CASCADE)
    if category == "laptop":
        cpu_model = models.CharField(max_length=200)

so if I were to go to the Django admin page and create an instance of the model and then choose "laptop" as the product from the drop-down list of existing "products", a new field would be available. I couldn't find anything about this in the documentation, so I'm wondering whether it's even possible.

Upvotes: 5

Views: 7620

Answers (4)

Y.Badreddine
Y.Badreddine

Reputation: 1

Making a field optional is not possible but you can use a generalized model called Product and two or more specialized ones called for example : ElectronicProduct that contains the field cpu_model and NonElectronicProduct, the two specialized models have to contain a OneToOneField to the Product model to ensure inheritance.

Upvotes: 0

Ilko
Ilko

Reputation: 1418

You can't do that in models. You can hide it in admin panel or you can make separate model for laptop. Or you can make field blank=True

Upvotes: 0

Benjamin
Benjamin

Reputation: 3477

I do not think it is possible because models defines databases tables so the column has to be present.

You can use the keyword blank=True to allow an object without this field.

Maybe you can customize the admin interface to hide the field in some cases.

Upvotes: 2

CoolestNerdIII
CoolestNerdIII

Reputation: 780

What you are asking for is not "technically" possible. A model relates a database object, and under traditional SQL rules, this isn't possible. You could instead make that field optional, and then customize the admin page's functionality.

Another potential option, though I do not have much experience with it, would be to use a NoSQL database in the case where you don't want to store NULL values in your db.

Upvotes: 6

Related Questions