A write simple application in Django 1.7. Is a model that represents the element of a linked list:
class TrainingUserWordSetItem(models.Model):
training_set = models.ForeignKey(TrainingUserWordSet)
user_word = models.ForeignKey(UserWord)
prev_item = models.ForeignKey("TrainingUserWordSetItem", null=True, default=None)
next_item = models.ForeignKey("TrainingUserWordSetItem", null=True, default=None)
When migrating I get an error:
hellodict.TrainingUserWordSetItem.next_item: (fields.E304) Reverse accessor for 'TrainingUserWordSetItem.next_item' clashes with reverse accessor for 'TrainingUserWordSetItem.prev_item'.
HINT: Add or change a related_name argument to the definition for 'TrainingUserWordSetItem.next_item' or 'TrainingUserWordSetItem.prev_item'.
hellodict.TrainingUserWordSetItem.prev_item: (fields.E304) Reverse accessor for 'TrainingUserWordSetItem.prev_item' clashes with reverse accessor for 'TrainingUserWordSetItem.next_item'.
HINT: Add or change a related_name argument to the definition for 'TrainingUserWordSetItem.prev_item' or 'TrainingUserWordSetItem.next_item'.
How make two self-referential foreign key fields?
Update:
Helped use related_name='+':
class TrainingUserWordSetItem(models.Model):
training_set = models.ForeignKey(TrainingUserWordSet)
user_word = models.ForeignKey(UserWord)
prev_item = models.ForeignKey("TrainingUserWordSetItem", null=True, default=None)
next_item = models.ForeignKey("TrainingUserWordSetItem", null=True, default=None, related_name='+')
Your intermediate model must contain one - and only one - foreign key to the source model (this would be Group in our example). If you have more than one foreign key, a validation error will be raised.
ForeignKey is a Django ORM field-to-column mapping for creating and working with relationships between tables in relational databases. ForeignKey is defined within the django. db. models. related module but is typically referenced from django.
To handle One-To-Many relationships in Django you need to use ForeignKey . The current structure in your example allows each Dude to have one number, and each number to belong to multiple Dudes (same with Business).
You could actually probably accomplish what you're attempting with one field. I believe this would work:
next_item = models.ForeignKey('self', null=True, default=None, related_name='prev_item')
Note the use of 'self'; according to the Django documentation, To create a recursive relationship – an object that has a many-to-one relationship with itself – use models.ForeignKey('self').
Additionally, I would recommend trying this with a OneToOneField, rather than a ForeignKey, assuming that every item will only ever have one previous and one next item.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With