过滤多对一模型

时间:2016-10-25 12:36:17

标签: python django filter many-to-one

我希望能够为用户分配车辆注册,当用户登录网站时,他们的主页应该有他们拥有的车辆注册列表。

但是我无法让模型类过滤外键。

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 %}

有人可以帮我解决我出错的地方吗?

由于

2 个答案:

答案 0 :(得分:1)

  

Django提供了一种强大而直观的方式来“跟踪”查找中的关系,在后台自动处理SQL JOIN。要跨越关系,只需使用跨模型的相关字段的字段名称,用双下划线分隔,直到到达所需的字段。

所以你的查询应该是

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

Reference

答案 1 :(得分:0)

您无法使用未命名的参数进行查询:

Vehicle.objects.filter(UserProfile.user)

在这种情况下,您需要:

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