簡體   English   中英

如何在django中的多個表之間進行查詢

[英]how to query between multi tables in django

請看一些片段:

1.Model UserProfile:

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.Model TimeLine:

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())

問題 :如何使image_id 'timelinedict'包含UserProfile的字段( image_idemail )。

提前致謝:)

您不需要做任何特殊操作,可以直接從TimeLine實例訪問這些屬性。

例如

for t in TimeLine.objects.all():
    print t.user.image_id, t.user.email

同樣,您也可以在模板中使用它。

問題:如何使image_id '包含UserProfile字段( image_idemail )。

它已經做到了:

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 %}
  1. 使用render快捷方式,而不是render_to_response render將返回正確的請求上下文 ,這在處理表單時很有用。 最好養成使用render的習慣。

  2. 不要使用locals() ; 因為您會將范圍中的每個變量發送到模板。 這絕不是你想要的。 顯式優於隱式。

您例如timelinedict實際上不是dict這是一個queryset包含由Timeline對象。

我認為使用下面的@property裝飾器將允許您將屬性附加到TimeLine模型對象。

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_id等直接在模板中訪問它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM