[Django]-Django 1.7: how to make ManyToManyField required?

9👍

On a database level… no, that’s not possible. Any enforcement of this will have to come from your application logic.

The reason is that every m2m relation has a record with a foreign key to both sides of the m2m relation. SQL cannot enforce the existence of the referencing side of a relationship, only of the referenced side of a relationship.

Furthermore, you can’t enforce it in your model either, because the Person has to be created and saved before you can assign any many-to-many relations.

Your only options are to enforce it in the form or the view.

In an InlineModelAdmin this can easily be done by specifying min_num (1.7+):

class PersonSkillsInline(admin.TabularInline):
    model = Person.skills.through
    min_num = 1
    extra = 2
👤knbk

Leave a comment