I want to make query works as follow 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
'''
models:
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)
because mobile_number isn't always filled in Winner model,what I want is a winner who has mobile number or who get the sms.So must join PrizeVerificationCodeSMSLog to make my purpose.
Only get winner is simple:
winners = models.Winner.objects.filter(lucky_draw_id=id).order_by('-created_on')[:10]
But I have no idea what filter can be added to join PrizeVerificationCodeSMSLog.
I have finally understood how to retrieve data I want in django.
If you want to get model A restricted by another model B which has a Foreign Key to A, do not try to use filter(). Because A don't know B,but B know A!Just retrieve A base B.
ForeignKey.related_nameandForeignKey.related_query_namein the docs.