Home > Enterprise >  django ManyToManyField unique
django ManyToManyField unique

Time:10-04

class Building(models.Model):
    address = models.CharField(max_length=20, primary_key=True)
    employers = models.ManyToManyField(
        settings.AUTH_USER_MODEL, related_name="employers",
        blank=True)

Suppose n users of model type User and m buildings of model type Building (m << n). I would like in the Admin page to be able to put users into building in the unique way:

  1. a user can be in maximum one building.
  2. a building can have many employers. It can be empty too.
  3. in the Admin page, in the Employers selection widget, in the UPDATE mode, exclude users that belong to another building. In the CREATE mode, show only users without a building.

Stack: Django, MySQL.

CodePudding user response:

So, basically you need inside User model one field with Foreign key relationship with Building and you can query it with related name.

example:

class User(AbstractUser):
"""
Your user model
"""
building = models.ForeignKey(Building, related_name='building_employers', on_delete...)
...

Later you can query employers with building_object.building_employers.all()

For question number 3, please check: https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#django.contrib.admin.TabularInline

  • Related