Django ManyToManyField unique
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)
Предположим, что есть n пользователей модели типа User и m зданий модели типа Building (m << n). Я хотел бы, чтобы на странице администратора можно было помещать пользователей в здания уникальным способом:
- a user can be in maximum one building.
- a building can have many employers. It can be empty too.
- 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.
Стек: Django, MySQL.
Итак, в основном вам нужно внутри модели User одно поле с внешней ключевой связью с Building, и вы можете запрашивать его с помощью связанного имени.
пример:
class User(AbstractUser):
"""
Your user model
"""
building = models.ForeignKey(Building, related_name='building_employers', on_delete...)
...
Позже вы можете запросить работодателей с помощью функции building_object.building_employers.all()
Для вопроса №3, пожалуйста, проверьте: https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#django.contrib.admin.TabularInline