Reputation: 8418
I have a simple model like this:
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()
users place bids for an item. Knowing that a user is allowed to place just one bid for each item. If I have the auction id, can I get all user objects (not simple usernames, like in a values_list()
) that placed a bid in that auction?
EDIT: I would also like to avoid using 'in'
Upvotes: 0
Views: 126
Reputation: 724
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
Upvotes: 1
Reputation: 599956
users = User.objects.filter(bid__item__auction_id=auction_id)
Upvotes: 4