5

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.

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

how would i "Customize the admin page's functionality" ? with js ?
The ability to customize it is outlined here. For what you are trying to do, you might be able to get away with using some of the features within the ModelAdmin. If not, then you may have to rely on further customizing it with some JS and/or CSS.
2

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.

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.