Use at least one value with many to many in Django?

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

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

I want every user (profile) to have at least one Foo. Foos may have zero or more user (s) s.

I would really like this to be done at the model and administrator level, but it’s enough to provide it in the admins.

If I understand correctly, "many" in Django-talk have a value of zero or more.

I need a ManyToOneOrMore relation. How can i do this?

Thanks,

Chris.

+10
django orm
source share
2 answers

You cannot force it at the model level as @Greg data, but you can apply it to the form by simply making the field you need. This will not stop anyone with shell level access from manually creating a UserProfile without foo, but it will force anyone to use the browser-based form creation method.

+5
source share

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

+7
source share

All Articles