2011-05-22 114 views
0

我有Django模型與一個throughmanytomany連接:Django的多對多,並通過對

class userProfile(models.Model): 
    boughtCoupons = models.ManyToManyField(Coupon, through='UserCoupons') 

class UserCoupons(models.Model): 
    user = models.ForeignKey(userProfile) 
    coupon = models.ForeignKey(Coupon) 
    date = models.DateField() 


class Coupon(models.Model): 
    name = models.CharField(max_length=10) 

我知道我可以每個人單獨使用和ID或東西來篩選得到的。

但是,我需要獲取穿透表的值與所有用戶的詳細信息(配置文件)。

那麼,我該如何做一個像JOIN一樣的東西,並在一個查詢中獲得一個UserCoupons + userProfile對呢? (所以我可以得到匹配的用戶配置文件無需額外的查詢?)

回答

1

您可以在UserCoupons直接查詢和使用select_related()在一個查詢中也獲取了相關對象:

UserCoupons.objects.select_related().filter(**your_filters) 

注意select_related()沒有按」 「向後」工作。這就是爲什麼您需要使用定義ForeignKey的類的經理來使其工作(在這種情況下爲UserCoupons)。

+0

好的,但我如何得到兩個對象呢?我得到一個優惠券對象列表 – 2011-05-26 07:56:32

+0

'user_coupon = UserCoupons.objects.select_related()。get(** filter);打印user_coupon.user;打印user_coupon.coupon;' – 2011-05-26 10:18:49

1

如果您使用的是Django 1.2或更低版本,那麼就我所知,jkbrzt的答案是唯一的解決方案,因爲在不使用原始SQL的情況下讓Django生成JOIN的唯一方法是使用select_related()或Django的double_ 下劃線表示法 - 在Django 1.2或更低版本中,它們都不能用於多對多關係。然而,在Django的雙 _underscore符號工作的許多一對多在Django 1.3,這樣你就可以做到以下幾點:

userProfile.objects.values('boughtCoupons__name', 'usercoupons__date') 

你必須列出所有你需要的領域,據我所知,有這種方法使得它有點痛苦,但永遠不會少於它的選擇。