如何在Django 1.8中联接表

时间:2019-02-14 09:38:47

标签: python mysql django

我试图在django模板中访问联接的数据,但是没有任何效果,我们将不胜感激。

Model1():
   project_code = Foreignkey(another table1)
   shot_code = charfield(primary_key = True)
   shot_name = charfield()
   sequence_name = Integerfield()

Model2():
   vendor_id = Foreignkey(another table2)
   shot_code = Foreignkey(Model1, on_delete= models.CASCADE)
   shot_rate = integerfield()
   shot_bid = integerfield()

我想展示

Select * from Model1 a, Model2 b, where a.shot_code = b.shot_code 
and model1.project_code = "XXX"

和要在模板中访问的列

1. Shot code
2. Shot name
3. Sequence name
4. Shot rate
5. Shot bid
6. Vendor id

我尝试了以下方法

1. Using Select_related
    result = only values of model2 is displayed
    unable to access model1's data, 
    error = 'QuerySet' object has no attribute model1

2 个答案:

答案 0 :(得分:1)

您希望它返回一个或多个实例吗?最好的方法仍然是使用select_related,例如:

Model2.objects.filter(shot_code__project_code=<your value>).select_related("shot_code")

对于具有多个Model2实例的查询集,如果只希望有一个实例,则在末尾添加.get()

或者,您可以添加.values(),而不是对两个相关模型进行操作,而获得类似dict的连接结果(尽管请注意,您将无法直接重用shot_code,因为它将与您的外键名称冲突):

Model2.objects.filter(shot_code__project_code=<your value>).annotate(
    sequence_name=F("shot_code__sequence_name"),
    shot_name=F("shot_code__shot_name"),
    real_shot_code=F("shot_code__shot_code")
).values(
    "sequence_name", "shot_name", "real_shot_code", "shot_rate", "shot_bid", "vendor_id"
)

和往常一样,我建议不要将您的ForeignKey命名为vendor_id,因为它将真实的ID放在vendor_id_id下,并且命名会有点不清楚。 / p>

答案 1 :(得分:0)

您可以使用Model2中设置的Model1查询对象并获取数据,请参见以下示例:

model1obj = Model1.objects.get(project_code = "XXX")
model2obj = Model2.objects.get(shot_code = model1obj)

# now access all the fields using model1obj  and model2obj