在Django中,以多对多关系强制实施至少一个值?

时间:2022-04-13 08:03:42

I have have a many-to-many relation in a Django(1.4) model.

我在Django(1.4)模型中有多对多的关系。

class UserProfile(models.Model):
    foos = models.ManyToManyField(Foo)

I want to enforce that each User(Profile) has at least one Foo. Foos can have zero-or-more User(Profiles)s.

我想强制每个用户(配置文件)至少有一个Foo。 Foos可以具有零个或多个用户(配置文件)。

I would love this to be enforced at the model and admin levels, but just enforcing it in the admin would be sufficient.

我希望这能在模型和管理员级别强制执行,但只需在管理员中执行它就足够了。

If I understand correctly, 'many' in Django-speak is zero-or-more.

如果我理解正确,Django发言中的'很多'是零或更多。

I want a ManyToOneOrMore relation. How can I do this?

我想要一个ManyToOneOrMore关系。我怎样才能做到这一点?

Thanks,

谢谢,

Chris.

克里斯。

2 个解决方案

#1


4  

You can't enforce this on at the model level as @Greg details, but you can enforce it on a form by simply making the field required. This won't prevent anyone with shell-level access from manually creating a UserProfile without a foo, but it will force anyone using a browser-based form method of creation.

您无法在模型级别将此强制实施为@Greg详细信息,但您可以通过简单地创建所需字段来在表单上强制执行此操作。这不会阻止任何具有shell级别访问权限的人在没有foo的情况下手动创建UserProfile,但它会强制任何人使用基于浏览器的表单创建方法。

#2


7  

Unfortunately, I don't think this is possible at the model level because ManyToMany data is saved separately from other model fields. You should be able to enforce it at the admin level by specifying a custom form, and writing a clean() method on the form.

不幸的是,我不认为这在模型级别是可行的,因为ManyToMany数据与其他模型字段分开保存。您应该能够通过指定自定义表单并在表单上编写clean()方法在管理员级别强制执行它。

#1


4  

You can't enforce this on at the model level as @Greg details, but you can enforce it on a form by simply making the field required. This won't prevent anyone with shell-level access from manually creating a UserProfile without a foo, but it will force anyone using a browser-based form method of creation.

您无法在模型级别将此强制实施为@Greg详细信息,但您可以通过简单地创建所需字段来在表单上强制执行此操作。这不会阻止任何具有shell级别访问权限的人在没有foo的情况下手动创建UserProfile,但它会强制任何人使用基于浏览器的表单创建方法。

#2


7  

Unfortunately, I don't think this is possible at the model level because ManyToMany data is saved separately from other model fields. You should be able to enforce it at the admin level by specifying a custom form, and writing a clean() method on the form.

不幸的是,我不认为这在模型级别是可行的,因为ManyToMany数据与其他模型字段分开保存。您应该能够通过指定自定义表单并在表单上编写clean()方法在管理员级别强制执行它。