疯狂的Django 之深度外键跨表查找之疯狂INNER JOIN
定义Model:
from django.db import models
class Moreinfo(models.Model):
weight = models.FloatField()
height = models.FloatField()
class Detail(models.Model):
sex = models.CharField(max_length=20)
age = models.IntegerField()
moreinfo = models.ForeignKey(Moreinfo)
class Usr(models.Model):
name = models.CharField(max_length=20)
money = models.FloatField()
detail = models.ForeignKey(Detail)
class Product(models.Model):
name = models.CharField(max_length=20)
price = models.FloatField()
class Record(models.Model):
buyer = models.ForeignKey(Usr, related_name='+',)
seller = models.ForeignKey(Usr, related_name='+',)
product = models.ForeignKey(Product)
conut = models.IntegerField()
查询语句:
>>> x=Record.objects.filter(Q(seller__detail__age__gt=20)|Q(buyer__detail__age__gt=20))
>>> print(x.query)
SELECT "tt_record"."id", "tt_record"."buyer_id", "tt_record"."seller_id", "tt_record"."product_id", "tt_record"."conut" FROM "tt_record" INNER JOIN "tt_usr" ON ("tt_record"."seller_id" = "tt_usr"."id") INNER JOIN "tt_detail" ON ("tt_usr"."detail_id" = "tt_detail"."id") INNER JOIN "tt_usr" T4 ON ("tt_record"."buyer_id" = T4."id") INNER JOIN "tt_detail" T5 ON (T4."detail_id" = T5."id") WHERE ("tt_detail"."age" > 20 OR T5."age" > 20)
整理如下:
SELECT "tt_record"."id", "tt_record"."buyer_id", "tt_record"."seller_id", "tt_record"."product_id", "tt_record"."conut"
FROM "tt_record"
INNER JOIN "tt_usr" ON ("tt_record"."seller_id" = "tt_usr"."id")
INNER JOIN "tt_detail" ON ("tt_usr"."detail_id" = "tt_detail"."id")
INNER JOIN "tt_usr" T4 ON ("tt_record"."buyer_id" = T4."id")
INNER JOIN "tt_detail" T5 ON (T4."detail_id" = T5."id")
WHERE ("tt_detail"."age" > 20 OR T5."age" > 20)