[英]conflict between OneToMany and OneToOne relationship in Django
I need to define a Meeting model which includes an organiser and a number of participants. 我需要定义一个会议模型,其中包括组织者和许多参与者。 All participants are derived from the standard User in auth module.
所有参与者均来自身份验证模块中的标准用户。
from django.db import models
from django.contrib.auth.models import User
class Meeting(models.Model):
organizer=models.ForeignKey(User)
participants=models.ManyToManyField(User)
However, when running syncdb, the I got the following error 但是,运行syncdb时,出现以下错误
Error: One or more models did not validate: hub.meeting: Accessor for field 'organizer' clashes with related m2m field 'User.meeting_set'.
错误:一个或多个模型未通过验证:hub.meeting:字段“ organizer”的访问者与相关的m2m字段“ User.meeting_set”冲突。 Add a related_name argument to the definition for 'organizer'.
在'organizer'的定义中添加related_name参数。 hub.meeting: Accessor for m2m field 'participants' clashes with related field 'User.meeting_set'.
hub.meeting:m2m字段“参与者”的访问者与相关字段“ User.meeting_set”冲突。 Add a related_name argument to the definition for 'participants'.
在“参与者”的定义中添加一个related_name参数。
Can anyone help me to solve this? 谁能帮我解决这个问题?
class Meeting(models.Model):
organizer=models.ForeignKey(User, related_name="meetings_orginizer")
participants=models.ManyToManyField(User, related_name="meetings_participants")
If you have a user object and you want to follow the relationship backwards to find either the meetings that user is an organizer of or meetings that the user is a participant of , you need to specifically name a 'related_name' field on the model to distinguish them. 如果您有一个用户对象,并且想要向后跟踪该关系以查找该用户是其组织者的 会议或该用户是其参加者的会议,则需要在模型上专门命名一个“ related_name”字段以区别他们。 Now you can follow the relationship backwards like so:
现在,您可以像下面这样向后跟踪关系:
me = User.objects.get(id=0)
# Meetings I'm organising
m1 = me.meetings_orginizer.all()
# Meetings I'm participating in
m2 = me.meetings_participants.all()
the problem (as stated by the error message) has to do with backwards relations. 问题(如错误消息所述)与反向关系有关。 when you define a foreign key (or many2many), django sets up a reverse relation User.meeting_set.
当您定义一个外键(或many2many)时,django会建立一个反向关系User.meeting_set。 however, since you have two relations, the reverse relations clash and you have to specify the related names manually.
但是,由于有两个关系,反向关系会发生冲突,因此必须手动指定相关名称。 see the docs here and here
在这里和这里查看文档
code as in answer above 代码如上面的答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.