2016-10-25 70 views
0

我希望能夠爲用戶分配車輛註冊,並且當用戶登錄到網站時,他們的主頁應該有他們擁有的車輛註冊表列表。在多對一模型上過濾

但是我不能讓模型類過濾外鍵。

views.py

@login_required 
def home(request): 
    # This is the basic user landing Page 
    veh_list = Vehicle.objects.filter(UserProfile.user) 
    return render(request, 'portal/home.html', {"veh_list": veh_list}) 

model.py

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

# Create your models here. 
class UserProfile(models.Model): 
    # This line is required. Links UserProfile to a User model instance. 
    user = models.OneToOneField(User) 

    # The additional attributes we wish to include. 
    compName = models.CharField(max_length = 20) 
    milkco = models.IntegerField() 


    # Override the __unicode__() method to return out something meaningful! 
    def __unicode__(self): 
     return self.user.username 

class Vehicle(models.Model): 
    vehid = models.CharField(max_length = 10) 
    company = models.ForeignKey(UserProfile, default = 1) 

    class Meta: 
     db_table = "vehicle" 

    def __unicode__(self): 
     return self.vehid 

home.html的

<!DOCTYPE html> 
{% extends 'portal/base.html' %} 

{% block title %}{{user.first_name }} {{ user.last_name }} Portal{% endblock %} 

{% block content %} 

    <p>This is the home Page</p> 
    {% if user.is_authenticated %} 
     <h4>Optiload says... hello {{ user.first_name }} {{ user.last_name }}!</h4> 
    {% endif %} 

    {% for veh in veh_list %} 
     {{ veh}} 
    {% endfor %} 

    {% if user.is_authenticated %} 
     <a href="/logout/">Logout</a><br/> 
    {% endif %} 
{% endblock %} 

有人能幫助我,我要去錯在何處?

感謝

+0

工作的呢? 'veh_list = Vehicle.objects.filter(company__user = request.user)' – Sagar

+0

@Sagar是的..這正是我需要的。 – Jim

+0

我將添加它作爲答案:) – Sagar

回答

1

Django還提供了一個功能強大,直觀的方式在looku中「追隨」關係ps,在幕後自動爲你處理SQL JOIN。要跨越關係,只需使用模型中相關字段的字段名稱(用雙下劃線分隔),直到您到達所需的字段。

所以您的查詢應該像

veh_list = Vehicle.objects.filter(company__user=request.user) 

Reference

0

你不能用未命名的參數進行查詢:

Vehicle.objects.filter(UserProfile.user)

在這種情況下,你想:

Vehicle.objects.filter(company=[your user])