我目前正在建立一个帮助台票务系统作为学校项目。我正在使用内置的django auth系统,我想从auth系统引用用户ID。例如,票证将分配给某个帮助台员工。我模特的一部分:
class Ticket(models.Model):
category = models.ManyToManyField(Category)
title = models.CharField(max_length=30)
submitted = models.DateTimeField(editable=False)
submitter = #reference to user
assignedTo = #reference to helpdesk employee
用户位于群组user
中,帮助台员工位于django auth系统的群组helpdeskemployee
中。
所以我尝试了这个:
class Ticket(models.Model):
category = models.ManyToManyField(Category)
title = models.CharField(max_length=30)
submitted = models.DateTimeField(editable=False)
submitter = models.OneToOneField(User)
assignedTo = user = models.OneToOneField(User)
但是在运行python manage.py syncdb
时会出现以下错误:
CommandError: One or more models did not validate:
deskman.ticket: Accessor for field 'submitter' clashes with related field 'User.ticket'. Add a related_name argument to the definition for 'submitter'.
deskman.ticket: Reverse query name for field 'submitter' clashes with related field 'User.ticket'. Add a related_name argument to the definition for 'submitter'.
deskman.ticket: Accessor for field 'assignedTo' clashes with related field 'User.ticket'. Add a related_name argument to the definition for 'assignedTo'.
deskman.ticket: Reverse query name for field 'assignedTo' clashes with related field 'User.ticket'. Add a related_name argument to the definition for 'assignedTo'.
deskman.ticket: Accessor for field 'assignedTo' clashes with related field 'User.ticket'. Add a related_name argument to the definition for 'assignedTo'.
deskman.ticket: Reverse query name for field 'assignedTo' clashes with related field 'User.ticket'. Add a related_name argument to the definition for 'assignedTo'.
答案 0 :(得分:6)
首先,您可能不想使用OneToOneField
。这意味着用户只能拥有一张单票。 ForeignKey
关系会更好。
class Ticket(models.Model):
category = models.ManyToManyField(Category)
title = models.CharField(max_length=30)
submitted = models.DateTimeField(editable=False)
submitter = models.ForeignKey(User)
assignedTo = models.ForeignKey(User)
您收到错误的原因是您与Ticket
的同一模型有两种关系。这意味着如果你有一个User
对象并且你试图反转它,那么你想要使用哪种关系并不清楚:
user.ticket_set.all()
# Do you want `submitter` tickets, or `assignedTo` tickets? It's not clear
要解决此问题,请为每个字段添加related_name
属性
class Ticket(models.Model):
category = models.ManyToManyField(Category)
title = models.CharField(max_length=30)
submitted = models.DateTimeField(editable=False)
submitter = models.ForeignKey(User, related_name="tickets_submitter")
assignedTo = models.ForeignKey(User, related_name="tickets_assignedto")
现在你可以分别得到两种反向关系:
user.tickets_submitter.all()
user.tickets_assignedto.all()