0

我有一个像这样的简单模型:

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,我能否获得在该拍卖中出价的所有用户对象(不是简单的用户名,例如 a values_list())?

编辑:我也想避免使用'in'

4

2 回答 2

4
users = User.objects.filter(bid__item__auction_id=auction_id)
于 2012-05-25T22:53:50.673 回答
1

It's probably possible to do it much easier, but this is the way I would try.

Add related names:

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()

Now, if you have these:

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)

Now, all the users with one or more bids in that auction is in the list

于 2012-05-25T23:02:57.747 回答