简体   繁体   中英

how to query between multi tables in django

See some snippets please:

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

Question : how can I make the var 'timelinedict' contain fields ( image_id , email ) of UserProfile.

Thanks in advance:)

You don't need to do anything special, you can directly access those attributes from instance of TimeLine .

For example

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

Similarly you can use that in template as well.

Question: how can I make the var 'timelinedict' contain fields ( image_id , email ) of UserProfile .

It already does:

from models import TimeLine
from django.shortcuts import render

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

In timeline.html :

{% for obj in objects %}
   {{ obj.user.email }}
   {{ obj.user.image_id }}
{% endfor %}
  1. Use the render shortcut, not render_to_response . render will return the correct request context , which is useful when you are processing forms. It is best to get into the habit of using render .

  2. Don't use locals() ; because you will send every variable in the scope to your template. This is never what you want. Explicit is better than implicit.

Your example for timelinedict isn't actually a dict it's a queryset containing TimeLine objects.

I think using the @property decorator as below will allow you to attach attributes to your TimeLine model objects.

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

Of course, you could just access them directly in your template via object.user.image_id, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM