我有一个这样的简单模型:
class Auction(models.Model):
name = models.CharField()
class Item(models.Model):
auction = models.ForeignKey(Auction)
name = models.CharField()
price = models.FloatField()
class Bid(models.Model):
item = models.ForeignKey(Item)
user = models.ForeignKey(User)
price = models.FloatField()
用户为商品出价。知道允许用户为每个项目仅放置一个出价。如果我有拍卖ID,我是否可以获得在该拍卖中出价的所有用户对象(不是简单的用户名,如values_list()
)?
编辑:我也想避免使用'in'
答案 0 :(得分:4)
users = User.objects.filter(bid__item__auction_id=auction_id)
答案 1 :(得分:1)
它可能更容易做到,但这是我尝试的方式。
添加相关名称:
from django.db import models
from django.contrib.auth.models import User
class Auction(models.Model):
name = models.CharField(max_length=20)
class Item(models.Model):
auction = models.ForeignKey(Auction,related_name="items")
name = models.CharField(max_length=20)
price = models.FloatField()
class Bid(models.Model):
item = models.ForeignKey(Item,related_name="bids")
user = models.ForeignKey(User,related_name="bids")
price = models.FloatField()
现在,如果你有这些:
a = Auction.objects.get(pk=auction_id)
users = set([]) #because there's no reason to have dupe users
for item in a.items.all():
for bid in item.bids.all():
users.add(bid.user)
现在,该拍卖中有一个或多个出价的所有用户都在列表中