Django - 清理字段,引用相关对象
Django - Clean a field, refer to a Related object
我有组和人,我希望在一个组中同名的人不能超过一个人...但在不同的组中没关系...很容易。我的代码:
class Group(model.Model):
name = models.CharField() #irrelevant
class Person(models.Model):
name = models.CharField(max_length=255, unique=False)
related_group = models.ForeignKey(Group)
def clean(self):
if self.related_group:
for pip in self.related_group.person_set.all():
if pip.name == self.name:
raise ValidationError("Name already exists in this Group")
我收到这个错误:
RelatedObjectDoesNotExist at /create/person/ # the url of creating the object
人无related_group.
我想问题是我需要找到一种方法来引用该组(在表格中)
谢谢。
您应该可以使用 unique_together
,然后您就不需要检查 clean
方法。
class Person(models.Model):
name = models.CharField(max_length=255, unique=False)
related_group = models.ForeignKey(BreadcrumbGroup)
class Meta:
unique together = [
('name', 'related_group'),
]
我有组和人,我希望在一个组中同名的人不能超过一个人...但在不同的组中没关系...很容易。我的代码:
class Group(model.Model):
name = models.CharField() #irrelevant
class Person(models.Model):
name = models.CharField(max_length=255, unique=False)
related_group = models.ForeignKey(Group)
def clean(self):
if self.related_group:
for pip in self.related_group.person_set.all():
if pip.name == self.name:
raise ValidationError("Name already exists in this Group")
我收到这个错误:
RelatedObjectDoesNotExist at /create/person/ # the url of creating the object
人无related_group.
我想问题是我需要找到一种方法来引用该组(在表格中) 谢谢。
您应该可以使用 unique_together
,然后您就不需要检查 clean
方法。
class Person(models.Model):
name = models.CharField(max_length=255, unique=False)
related_group = models.ForeignKey(BreadcrumbGroup)
class Meta:
unique together = [
('name', 'related_group'),
]