[Django]-Django: related_name attribute (DatabaseError)

1πŸ‘

βœ…

As it says, voting_users, needs a related_name argument because it clashes with an already defined related field, message_set (an automagic property created by django for your first ForeignKey, Message.user)

http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.related_name

You must supply a related name argument to either of your ForeignKey / m2m fields to define a unique accessor for the reverse relationship.

For example, the reverse relationship for the Message model on UserProfile is UserProfile.message_set. If you have two ForeignKeyβ€˜s you’re attempting to create two different reverse relationships with the same UserProfile.message_set method.

user = models.ForeignKey(UserProfile, related_name="message_user")

...
# would create a UserProfile.message_user manager.
userprofile.message_user.all() # would pull all message the user has created.
userprofile.message_set.all() # would pull all Messages that the user has voted on.

0πŸ‘

The problem is that both voting_users and message_set have the same attribute name user. related_name allows you to define an alias for one of the attributes that you can use to avoid name conflicts.

(Edit: Wrong link)

http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.related_name

This question is very similar to another question listed here:
Django: Why do some model fields clash with each other?

πŸ‘€Nick Ruiz

Leave a comment