就是因为没有设置外键,还想关联查询。怎么搞嘞,下面就是解决方案哦。
我们先来准备下要用的Model:
class Author(models.Model):
name = models.Char(max_length=16, null=False, help_text='作者姓名')
work_age = models.Integer(null=False, help_text='作者工龄')
class Meta:
db_table = 'author'
# 这里为了防止,author_id 和外键使用混淆,这里没有设计author_id字段,而是使用 author_name
class Books(models.Model):
name = models.Char(max_length=256, null=False, help_text='书名')
author_name = models.Char(max_length=16, null=False, help_text='作者姓名')
class Meta:
db_table = 'books'
# 现在就是见证奇迹的时刻
# 我现在要联查,书名和作者工龄。。。奇怪的查询
result_qs = Books.objects.extra(
tables=['author'],
where=['author.name=books.author_name'],
select={'author_w_age': 'author.work_age'} # 如果要获取关联表的字段,要在这里处理一下,不然获取不到的。
).values('name', 'author_name', 'author_w_age')
# 上述相当于
"""
select books.name, books.author_name, author.work_age author_w_age
from books, author
where books.author_name = author.name
"""