从一个模型查询数据,从另一个模型过滤

时间:2018-09-07 19:16:03

标签: python django

我想显示一个表中的值,但是根据另一个表中的值过滤这些值。

例如:我要显示来自data / models.py的值,这些值由CustomUser表(accounts / models.py)中的customer_tag过滤。 这些是相关的表,但是我无法找出正确的语法来过滤该视图。 有任何想法吗?还是我当前的模式无法做到这一点。

data / views.py

from django.views.generic import ListView, DetailView
from django.views.generic.edit import UpdateView, DeleteView, CreateView
from django.urls import reverse_lazy
from .models import Data
from django.contrib.auth.mixins import LoginRequiredMixin
from rest_framework import generics
from .models import Data
from accounts.models import CustomUser
from .serializers import DataSerializer
from .permissions import IsAuthorOrReadOnly

class DataListView(LoginRequiredMixin,ListView):
    queryset = Data.objects.all()
    context = {
        "object_list": queryset
    }
    template_name = 'data_list.html'
    login_url = 'login'

帐户/模型.py

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

class CustomUser(AbstractUser):
    customer_Tag = models.CharField(max_length=50,)
    isAdmin = models.BooleanField(default = False,)
    notifications = models.BooleanField(default = True,)
    deviceSerial= models.CharField(max_length=50,)
    machineName= models.CharField(max_length=50,default="ESP1",)
    machineDescription = models.CharField(max_length=200,)

class Customer(models.Model):
    customerTag= models.CharField(max_length=50,) 
    customerName = models.CharField(max_length=50,)
    mainContact = models.CharField(max_length=100,default='',)
    Address = models.CharField(max_length=100,default='',)
    city = models.CharField(max_length=100,default='',)
    website = models.URLField(max_length=100,default='',)
    phone = models.IntegerField(default=0,)

    def __str__(self):
        return self.customerName

data / models.py

from django.db import models
from django.conf import settings
from django.contrib.auth import get_user_model


class Data(models.Model):
    author = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,)
    tempData= models.CharField(max_length=50,blank=True,)
    humidData= models.CharField(max_length=50,blank=True,)


def __str__(self):
    return str(self.author)

2 个答案:

答案 0 :(得分:1)

如果我对您的理解正确,我认为您正在寻找过滤查询的key__field参数。因此,在您的情况下,类似

Data.objects.filter(author__customer_tag='tag-you-are-looking-for')   # double underscores after author

希望这能回答您的问题!

答案 1 :(得分:1)

所有内容都在文档中:https://docs.djangoproject.com/en/2.1/topics/db/queries/#lookups-that-span-relationships

在过滤器中使用双下划线__查询相关模型的字段。

在这种情况下,您需要覆盖get_queryset类的DataListView方法以返回过滤的查询集:

class DataListView(LoginRequiredMixin,ListView):
...
def get_queryset(self):
    return self.queryset.filter(author__customerTag=self.request.user.customerTag)