Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在django中查询多个表_Python_Sql_Django_Orm - Fatal编程技术网

Python 如何在django中查询多个表

Python 如何在django中查询多个表,python,sql,django,orm,Python,Sql,Django,Orm,请看一些片段: 1.模型用户配置文件: from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) email = models.EmailField(unique=True) HEAD_CHOICE = ( ('

请看一些片段:

1.模型用户配置文件:

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user  = models.ForeignKey(User, unique=True)
    email = models.EmailField(unique=True)

    HEAD_CHOICE = (
        ('1', 'M'),
        ('2', 'F'),
    )
    image_id = models.CharField(max_length=2,  choices=HEAD_CHOICE, default='2')
2.模型时间线:

from django.db import models
from django.contrib.auth.models import UserProfile

class TimeLine(models.Model):
     user  = models.ForeignKey(UserProfile)
3.TimeLine的views.py

from models import TimeLine
from django.shortcuts import render_to_response

def index(request):
   timelinedict = TimeLine.objects.all()
   return render_to_response('timeline.html', locals())
问题:如何使var
'timelinedict'
包含UserProfile的字段(
image\u id
email


提前感谢:)

您的
timelinedict
示例实际上不是
dict
而是包含时间线对象的
查询集

我认为使用下面的
@property
装饰器可以将属性附加到时间线模型对象

class TimeLine(models.Model):
    user  = models.ForeignKey(UserProfile)

    @property
    def image_id(self):
        return self.user.image_id

    @property
    def email(self):
        return self.user.email

当然,您可以通过object.user.image\u id等直接在模板中访问它们。

您不需要做任何特殊的事情,您可以直接从
时间线的实例访问这些属性

比如说

for t in TimeLine.objects.all():
    print t.user.image_id, t.user.email
同样,您也可以在模板中使用它

问题:如何使变量“timelinedict”包含字段
UserProfile
的(
image\u id
email

它已经做到了:

from models import TimeLine
from django.shortcuts import render

def index(request):
   timelinedict = TimeLine.objects.all()
   return render(request, 'timeline.html', {'objects': timelinedict})
timeline.html
中:

{% for obj in objects %}
   {{ obj.user.email }}
   {{ obj.user.image_id }}
{% endfor %}
  • 使用
    渲染
    快捷方式,而不是
    渲染到响应
    <代码>渲染
  • 将返回正确的请求上下文,这在处理表单时非常有用。最好养成使用
    render
    的习惯

  • 不要使用
    locals()
    ;因为您将把作用域中的每个变量都发送到模板。这永远不是你想要的。显式比隐式好


  • 作品好的,你能告诉我为什么不使用render\u to\u response和为什么不使用locals()render很好,但是如果我知道我将通过locals()发送什么,我可以使用它,因为它让我的手指感觉更好。thxJust a suggestion(与您的问题无关):如果您希望从父表queryset访问外键表元素,则使用获取父表。这肯定会保存一些数据库点击。