使用django查询语言查询连接对象
Using django query language to query connected objects
我刚开始使用 django 查询语言,遇到了一些困难。我想要方法 get_present_users() return 所有连接到某个 Drink 对象的用户,以及 "Presence" 对象。我知道我可以获得所有相关的存在对象:
Presence.objects.filter(event=self.pk)
但是,我想不出将此查询集转给所有用户的方法。你们能帮帮我吗?
class Drink(BaseModel):
date = models.DateField()
comments = models.TextField(blank=True)
class Presence(BaseModel):
event = models.ForeignKey(Drink)
submitted_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='presence_submitted_by')
present_user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='presence_present_user')
如果您尝试编写一个函数来获取所有可以通过 Presence
对象 you can make use of the reverse relationship of a User to a Presence. 与 Drink
关联的 Users
而不是尝试从 Presence
获取 Users
.
的列表
from django.contrib.auth.models import User
...
class Drink(model.Models):
...
def get_present_users(self):
return User.objects.filter(presence_present_user__event=self)
...
这将允许你写:
drink = Drink.objects.get(id=1)
print(drink.get_present_users())
>> [<User: >, <User: >]
我刚开始使用 django 查询语言,遇到了一些困难。我想要方法 get_present_users() return 所有连接到某个 Drink 对象的用户,以及 "Presence" 对象。我知道我可以获得所有相关的存在对象:
Presence.objects.filter(event=self.pk)
但是,我想不出将此查询集转给所有用户的方法。你们能帮帮我吗?
class Drink(BaseModel):
date = models.DateField()
comments = models.TextField(blank=True)
class Presence(BaseModel):
event = models.ForeignKey(Drink)
submitted_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='presence_submitted_by')
present_user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='presence_present_user')
如果您尝试编写一个函数来获取所有可以通过 Presence
对象 you can make use of the reverse relationship of a User to a Presence. 与 Drink
关联的 Users
而不是尝试从 Presence
获取 Users
.
from django.contrib.auth.models import User
...
class Drink(model.Models):
...
def get_present_users(self):
return User.objects.filter(presence_present_user__event=self)
...
这将允许你写:
drink = Drink.objects.get(id=1)
print(drink.get_present_users())
>> [<User: >, <User: >]