Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enforce at least one value in a many-to-many relation, in Django?

Tags:

orm

django

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

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.

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.

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

Thanks,

Chris.

like image 346
fadedbee Avatar asked May 07 '12 10:05

fadedbee


People also ask

How does Django handle many-to-many relationship?

Behind the scenes, Django creates an intermediary join table to represent the many-to-many relationship. By default, this table name is generated using the name of the many-to-many field and the name of the table for the model that contains it.

How fetch data from many-to-many field in Django?

A ManyToManyField in Django is a field that allows multiple objects to be stored. This is useful and applicable for things such as shopping carts, where a user can buy multiple products. To add an item to a ManyToManyField, we can use the add() function.

How do I create a one to many relationship in Django?

To handle One-To-Many relationships in Django you need to use ForeignKey . The current structure in your example allows each Dude to have one number, and each number to belong to multiple Dudes (same with Business).

What is ForeignKey in Django?

ForeignKey is a Django ORM field-to-column mapping for creating and working with relationships between tables in relational databases.


1 Answers

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.

like image 144
Chris Pratt Avatar answered Oct 05 '22 13:10

Chris Pratt