如何为Django的Hotel模型添加多个授权访问用户?
Got it, let's fix this so you can add multiple authorized users to each Hotel. The issue right now is that ForeignKey only links a hotel to one single user—we need a many-to-many relationship to support multiple users. Here are two approaches based on your needs:
1. Basic Many-to-Many (No Extra Metadata)
If you just need to track which users have access without additional details like roles or authorization dates, update your Hotel model like this:
from django.contrib.auth.models import User from django.db import models class Hotel(models.Model): # Replace ForeignKey with ManyToManyField for multiple users authorized_users = models.ManyToManyField(User, verbose_name="Utilisateurs autorisés") code = models.CharField(max_length=500,verbose_name="Code hôtel", default="N/A") contact_rh = models.EmailField(max_length=150,verbose_name="Contact RH", default="N/A") contact_gm = models.EmailField(max_length=150,verbose_name="Contact GM", default="N/A") payday = models.CharField(max_length=500,verbose_name="Jour de paye prévu du mois") hotel = models.CharField(max_length=500,verbose_name="Nom de l'hôtel") planning = models.ImageField(default='default.jpg', upload_to='Planning mois en cours') def __str__(self): return self.hotel
Quick Tips:
- Django automatically creates a hidden junction table in the database to link hotels and users.
- In the Django admin, you’ll get a multi-select widget to easily add/remove authorized users.
- To access a hotel's users in code:
hotel.authorized_users.all() - To add a user programmatically:
hotel.authorized_users.add(user_instance)
2. Many-to-Many with Extra Metadata (e.g., User Role)
If you need to store additional info about each authorized user (like their role in the hotel, or when they were granted access), use a custom through model to define the junction table explicitly:
from django.contrib.auth.models import User from django.db import models class HotelUserAccess(models.Model): hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) role = models.CharField(max_length=100, verbose_name="Rôle", choices=[ ('manager', 'Manager'), ('staff', 'Personnel'), ('viewer', 'Observateur') ]) granted_at = models.DateTimeField(auto_now_add=True, verbose_name="Accès accordé le") class Meta: unique_together = ('hotel', 'user') # Prevent duplicate entries for the same hotel+user class Hotel(models.Model): authorized_users = models.ManyToManyField( User, through=HotelUserAccess, verbose_name="Utilisateurs autorisés" ) # ... keep all your existing fields ... def __str__(self): return self.hotel
Key Notes:
- The
throughparameter tells Django to use your custom junction model instead of the default one. - In the admin, register the
HotelUserAccessmodel or add an inline form to the Hotel admin to manage the extra fields easily. - To access access details:
hotel.hoteluseraccess_set.all()returns objects with user, role, and grant date.
Final Steps to Apply Changes
After modifying your model, run these commands to update the database:
python manage.py makemigrations python manage.py migrate
That's it! You can now manually add multiple authorized users to each hotel via the Django admin or your custom views.
内容的提问来源于stack exchange,提问作者user11005819

