Django manytomany and through pair
I have django models with a manytomany
connection with a through
class:
class userProfile(models.Model):
boughtCoupons = models.ManyToManyField(Coupon, through='UserCoupons')
class UserCoupons(m开发者_运维问答odels.Model):
user = models.ForeignKey(userProfile)
coupon = models.ForeignKey(Coupon)
date = models.DateField()
class Coupon(models.Model):
name = models.CharField(max_length=10)
I know how I can get each of them individually using and ID or something to filter.
But, I need to get the Through table's value with all the user's details (profile).
So how can I do something like a JOIN, and get a UserCoupons + userProfile pair in a single query ? ( So I can get the matching user profile without an extra query ?)
You can query directly on UserCoupons
and use select_related()
to fetch also the related objects in one query:
UserCoupons.objects.select_related().filter(**your_filters)
Note that select_related()
doesn't work "backwards". That's why you need to use a manager of the class that defines the ForeignKey
to make it work (UserCoupons
in this case).
If you are using Django 1.2 or less version then jkbrzt's answer is the only solution as far as I know, since the only way to get Django to generate JOINs, without using raw SQL, is to use either select_related()
or Django's double_underscore notation - neither of which work on many-to-many relationships in Django 1.2 or less. However, Django's double_underscore notation work on many-to-many in Django 1.3, so you can do the following:
userProfile.objects.values('boughtCoupons__name', 'usercoupons__date')
You have to list all the fields that you need, as far as I know, with this method which makes it a bit of a pain but never the less it is an option.
精彩评论