Django: related_name attribute (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__(s开发者_开发问答elf):
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'm actually new to django and i don't get it how i should use related_name attribute.
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.
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?
精彩评论