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.
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.
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.
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).
ForeignKey is a Django ORM field-to-column mapping for creating and working with relationships between tables in relational databases.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With