Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django-清除字段,引用相关对象_Python_Django_Foreign Key Relationship - Fatal编程技术网

Python Django-清除字段,引用相关对象

Python Django-清除字段,引用相关对象,python,django,foreign-key-relationship,Python,Django,Foreign Key Relationship,我有团队和人,我希望在一个团队中不能有多个同名的人。。。但在不同的群体中,这没关系。。。很简单。我的代码: class Group(model.Model): name = models.CharField() #irrelevant class Person(models.Model): name = models.CharField(max_length=255, unique=False) related_group = models.ForeignKey(Gro

我有团队和人,我希望在一个团队中不能有多个同名的人。。。但在不同的群体中,这没关系。。。很简单。我的代码:

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
此人没有相关的团队

我想问题是我需要找到一种方法来引用该组(在表单中) 谢谢。

您应该能够使用,这样您就不需要在
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'), 
       ] 

这是可行的,但遗憾的是,这会引发“完整性错误”而不是“验证错误”,我能做些什么来引发验证错误吗?首先,为什么它没有得到它应该得到的相关组?如果您使用模型表单,它应该为您一起验证
unique\u
,除非您将其中一个字段从表单中排除。你能展示你的观点吗?@Alasdair你应该在你的回答中包括
get\u或\u create
和/或
update\u或\u create
的用法,以展示如何创建/更新一个人。@Alasdair我确实没有将组添加到我的模型表单中,我昨天修复了它(并添加了一个costum clean方法来验证它),谢谢你的回答@schillingt我不确定我会推荐
get\u或\u create
方法,因此我将其从答案中删除,最好添加为单独的答案。我认为应该可以在创建/更新人员之前进行验证,因此不必使用
get\u或\u create