Django Property: related_name (DatabaseError)

I have this problem with my models.

class Message(models.Model):
    user = models.ForeignKey(UserProfile)
    text = models.TextField(max_length=160)
    voting_users = models.ManyToManyField(UserProfile)

    def __unicode__(self):
        return self.text

and

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)

    def __unicode__(self):
        return self.user.username

I get this error when I try to call message.voting_users:

message: Accessor for m2m field 'voting_users' clashes with related field
'UserProfile.message_set'. Add a related_name argument to the definition for
'voting_users'.

I am really new to django and I don't understand how to use the related_name attribute.

+3
source share
2 answers

As said, the voting_usersrelated_name argument is required because it encounters an already defined related field, message_set(an auto-magmatic 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 specify the associated name argument in any of the ForeignKey / m2m fields to define a unique accessor for feedback.

, Message UserProfile UserProfile.message_set. ForeignKey, UserProfile.message_set.

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.
+1

Source: https://habr.com/ru/post/1796026/


All Articles