You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Django的Hotel模型添加多个授权访问用户?

Solution for Adding Multiple Authorized Users to Your Hotel Model

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 through parameter tells Django to use your custom junction model instead of the default one.
  • In the admin, register the HotelUserAccess model 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:03:29