简体   繁体   中英

Django, How to change “blank” attribute of field from parent model?

I got two models, for example:

Parent(models.Model):
    mytext= models.Chafield(max_lenght=250, blank=True)

Child(Parent):
    mytext_comment=models.Chafield(max_lenght=250)

But in child I want mytext to be obligatory. Do it will be sufficient to invoke mytext.blank=False in child __init__ ? Caution this are not abstract methods because I want to be able to use Manager on Parent (Parent.objects.all() for example)

I don't think its possible. From Django Documentation :

This restriction only applies to attributes which are Field instances. Normal Python attributes can be overridden if you wish. It also only applies to the name of the attribute as Python sees it: if you are manually specifying the database column name, you can have the same column name appearing in both a child and an ancestor model for multi-table inheritance (they are columns in two different database tables).

PS: I tried to like you suggested, but I get error like unicode object has no attribute blank

Hmm you can try this solution:

Parent(models.Model):
    mytext= models.Chafield(max_lenght=250, blank=True)

Child(Parent):
    mytext_comment=models.Chafield(max_lenght=250)
Child._meta.get_field('mytext').blank = True

Can you please let me know if it works ?

As the discussion goes on I think the correct answer is:

You don't do it on model level. I should do this kind of validation on form level not in a model. Best places are: form fields parameters or form clean method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM