用django连接表

ato*_*cal 4 python django

queryObj = Rating.objects.select_related(
    'Candidate','State','RatingCandidate','Sig','Office','OfficeCandidate').get(
        rating_id = ratingId, 
        ratingcandidate__rating = ratingId,
        ratingcandidate__rating_candidate_id = \
             officecandidate__office_candidate_id)
Run Code Online (Sandbox Code Playgroud)

这行给了我一个错误.我正在尝试使用主键和常规ID链接许多不同的表.最后一个选择是问题:

ratingcandidate__rating_candidate_id = officecandidate__office_candidate_id.  
Run Code Online (Sandbox Code Playgroud)

我需要跳过才能获得所有数据.

S.L*_*ott 13

我正在尝试使用主键和常规ID链接许多不同的表.

不要试图"加入"表格.这不是SQL.

您必须执行多次获取才能从许多不同的表中获取数据.

select_related你能证明自己有瓶颈之前别担心.

只需根据需要从各个类中进行各种GET.

让我们关注候选人和评级.

class Rating( Model ):
    ...

class Candidate( Model ):
    rating = Models.ForeignKey( Rating )
Run Code Online (Sandbox Code Playgroud)

做这个.

r = Rating.objects.get( id=rating_id )
c = r.candidate_set.all()
Run Code Online (Sandbox Code Playgroud)

这将获得评级和所有具有该评级的候选人.这实际上是SQL连接的内容:它是两次提取.在Django ORM中,只需尽可能简单地写两个提取.让Django(和你的数据库)为你缓存一些东西.

要在模板表单的单行中显示多个表的元素,请执行此操作.

在视图中:

r = Rating.objects.get( id=rating_id )
return render_to_response( some_form, { 'rating':r } )
Run Code Online (Sandbox Code Playgroud)

在模板中:

Rating: {{rating}}.  Candidates: {% for c in rating.candidate_set.all %} {{c}} {%endfor%}
Run Code Online (Sandbox Code Playgroud)

等等.

您只需在模板中的对象中"导航"以显示所请求的信息.