The definition of ForeignKey of abstract base class in Django

Source: Internet
Author: User

Class base (models. Model):    user = models. ForeignKey (User)        class Meta:         abstract =true

The above is the definition of an abstract base class, with only one public field user,

Class A (Base):    Applier = models. ForeignKey (User)

Then there will be an error, as follows:

Commanderror:one or more models didn't validate:core.a:accessor for field ' user ' clashes with related field ' User.a_set ‘. Add a related_name argument to the definition for ' user '. Core.a:accessor for field ' applier ' Clashes with related field ' User.a_set '. Add a related_name argument to the definition for ' applier '.

A simple translation is: an object of Class A has two associated fields pointing to the same user class. and the association name is the same, all A_set

The solution is to avoid conflicts. By default, the name of the associated object is the lowercase object name plus ' _set '. Therefore, the specified related_name is displayed to resolve this issue.

Method One, in the subclass of the relevant reference to the same class in the field, add the Related_name attribute, as follows:

Class A (Base):    Applier = models. ForeignKey (User, related_name= ' Some_other_set ')

However, this action is too large (each subclass is modified), so it is best to add flexible support in the abstract base class, as follows:

Method Two:

Class base (models. Model):    user = models. ForeignKey (User, related_name = ' base_% (app_label) s_% (Class) s ')        class Meta:         abstract =true

This does not necessarily mean that you can avoid naming conflicts by 100%. If the subclass has other fields that are exactly foreignkey to user, and its Related_name property is set to ' base_% (App_label) s_% (Class) s ', there is a problem, but the probability is minimal.

Note that App_label seems to be no longer supported since 1.7.

The definition of ForeignKey of abstract base class in Django

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.