我有以下型号, 用户
class User(AbstractBaseUser, PermissionsMixin, Base):
email = models.EmailField(db_index=True, unique=True, max_length=255)
mobile = PhoneNumberField(null=True)
username = models.CharField(db_index=True, null=False, unique=True, max_length=255)
基类
class Room(Base):
name = models.CharField(db_index=True, unique=True, max_length=255)
status = models.CharField(default=RoomStatus.ACTIVE, max_length=256, null=True)
members = models.ManyToManyField(User)
last_activity = models.DateTimeField(default=timezone.now)
和两个孩子
class LeagueRoom(Room):
league = models.ForeignKey(League, on_delete=models.CASCADE, null=True)
location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True)
class ClubRoom(Room):
club = models.ForeignKey(Club, on_delete=models.CASCADE, null=True)
location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True)
我想为用户访问leagueroom_set
。我不确定该怎么做。该用户当前具有属性room_set
,但是我希望访问特定的room_set。有人可以帮我吗?
答案 0 :(得分:2)
您可以从另一端开始:
league_rooms = LeagueRoom.objects.filter(members=my_user)
答案 1 :(得分:1)
我认为您希望Room成为抽象的基类。然后,您尝试执行的操作将起作用。 https://docs.djangoproject.com/en/2.1/topics/db/models/#model-inheritance
class Room(models.Model):
name = models.CharField(db_index=True, unique=True, max_length=255)
# other fields
…
class Meta:
abstract = True
如果Room不能是抽象类,则必须将Member字段从Room移到每个子类中才能使用内置关系。
class LeagueRoom(Room):
league = models.ForeignKey(League, on_delete=models.CASCADE, null=True)
location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True)
members = models.ManyToManyField(User)
# same with ClubRoom
我想到的第三种方法是在每个子类上设置一个type属性,以便可以将room_set过滤为所需的房间类型。
class LeagueRoom(Room):
…
type = models.CharField(max_length=10, default='league')
…
然后在其他地方:
room_set.filter(type='league')