简体   繁体   中英

Foreign Keys clash with related field in Django Model

I'm working on a model class that will represent the relationship of one family member to another (part of a geneology feature)

My Class is:

class FamilyLink(models.Model):
    from_legacy = models.ForeignKey(Legacy)
    to_legacy = models.ForeignKey(Legacy)

    class Meta:
        unique_together = ("from_legacy", "to_legacy")

When I try and migrate I get the following error message:

CommandError: One or more models did not validate: archive.familylink: Accessor for field 'from_legacy' clashes with related field 'Legacy.familylink_set'. Add a related_name argument to the definition for 'from_legacy'. archive.familylink: Accessor for field 'to_legacy' clashes with related field 'Legacy.familylink_set'. Add a related_name argument to the definition for 'to_legacy'.

It seem my issue is having two foreignKey's in the same class both pointing to the same class (in this case the "Legacy" class). Does anyone know how I can be resolve/work around this?

I appreciate the thoughts and expertise.

The error message is quite explanatory:

class FamilyLink(models.Model):
    from_legacy = models.ForeignKey(Legacy, related_name = 'familylink_from_legacy')
    to_legacy = models.ForeignKey(Legacy, related_name = 'familylink_to_legacy')

By default, if no related_name attribute is set, the relatedname is set to familylink_set and since 2 different fields from the same relation, it causes the issues.

Read more on related_name attribute here

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