python – Django模型查询使用join

前端之家收集整理的这篇文章主要介绍了python – Django模型查询使用join前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我想使查询工作如下sql

sql_str = '''
    select * from luckydraw_winner W
    inner join luckydraw_prizeverificationcodesmslog L on W.id =L.winner_id
    where W.lucky_draw_id = %s
    limit 10
'''

楷模:

class Winner(models.Model):
    lucky_draw = models.ForeignKey(LuckyDraw)
    participation = models.ForeignKey(Participation)
    prize = models.ForeignKey(Prize)
    mobile_number = models.CharField(max_length=15,null=True,default = None)

class PrizeVerificationCodeSMSLog(models.Model):
    winner = models.ForeignKey(Winner)
    mobile_number = models.CharField(max_length=15,db_index=True)
    created_on = models.DateTimeField(auto_now_add=True)

因为mobile_number并不总是在Winner模型中填充,我想要的是拥有手机号码或获得短信的赢家.所以必须加入PrizeVerificationCodeSMSLog才能达到我的目的.
只有赢家很简单:

winners = models.Winner.objects.filter(lucky_draw_id=id).order_by('-created_on')[:10]

但我不知道可以添加什么过滤器来加入PrizeVerificationCodeSMSLog.

我终于明白了如何在django中检索我想要的数据.

如果要让模型A受到另一个具有A外键的模型B的限制,请不要尝试使用filter().因为A不知道B,但B知道A!只需检索A基B.

最佳答案
尝试

logs = PrizeVerificationCodeSMSLog.objects.filter(winner__lucky_draw_id=id).order_by('-created_on')
winners = logs.select_related("winner")[:10]

这会生成以下查询

SELECT "prizeverificationcodesmslog"."id","prizeverificationcodesmslog"."winner_id","prizeverificationcodesmslog"."mobile_number","prizeverificationcodesmslog"."created_on","winner"."id","winner"."lucky_draw_id","winner"."participation_id","winner"."prize_id","winner"."mobile_number" 
FROM "prizeverificationcodesmslog" 
INNER JOIN "winner" ON ("prizeverificationcodesmslog"."winner_id" = "winner"."id") 
WHERE "winner"."lucky_draw_id" = 1  
ORDER BY "prizeverificationcodesmslog"."created_on" 
DESC LIMIT 10;

我不确定您的要求是什么,但您可能希望通过Max PrizeVerificationCodeSMSLog进行聚合

https://docs.djangoproject.com/en/1.5/topics/db/aggregation/

原文链接:https://www.f2er.com/python/439707.html

猜你在找的Python相关文章