我有4个型号。
class User(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField()
class Subscription(models.Model):
user_id = models.ForeignKey(User)
title = models.CharField()
class Address(models.Model):
user_id = models.ForeignKey(User)
street = models.CharField()
class Wallet(models.Model):
user_id = models.ForeignKey(User)
balance = models.DecimalField(max_digits=6, decimal_places=2)
在这里,我想获得订阅行以及受尊重的用户地址和钱包余额。这可以在单个查询(ORM)中检索吗?
我听说过 select_related()和 prefetch_related()。但不确定如何将所有内容放在一个查询集中。
如何以pythonic方式实现这一目标?
答案 0 :(得分:0)
首先从FK字段中删除_id
。您还有subscription.user_id
(int)和subscription.user
User
。现在你必须写subscription.user_id_id
来访问id。
您是否了解用户可以在db设计中拥有多个钱包和地址?
使用ORM在单个查询中无法执行此操作。但是可以在3个查询中完成(不管记录多少)。
<强>更新:强>
class User(models.Model):
name = models.CharField()
class Subscription(models.Model):
user = models.ForeignKey(User, related_name='subscriptions')
title = models.CharField()
class Address(models.Model):
user = models.ForeignKey(User, related_name='addresses')
street = models.CharField()
class Wallet(models.Model):
user = models.ForeignKey(User, related_name='wallets')
balance = models.DecimalField(max_digits=6, decimal_places=2)
subscriptions = Subscription.objects.select_related('user').prefetch_related(
'user__wallets', 'user__addresses')
for s in subscriptions:
print(s.user.name)
for wallet in s.user.wallets.all():
print(wallet.balance)
for address in s.user.addresses.all():
print(address.street)
答案 1 :(得分:0)
您是否尝试过关注文档中的this snippet?
拥有User
对象实例,您可以执行以下操作来访问订阅:
user.subscription_set.all()
它需要单独调用不同的管理员才能收集所有数据。