简体   繁体   English

相关对象的Django查询集

[英]Django queryset of related objects

Having the following model:具有以下模型:

class Company(models.Model):
    name = models.CharField(max_length=10)
    
class Department(models.Model):
    name = models.CharField(max_length=10)
    company = models.ForeignKeyField(to=Company)
    persons = models.ManyToManyField(to=Person, on_delete=models.PROTECT)

class Person(models.Model):
    name = models.CharField(max_length=10)


I would like to get a queryset of all persons in a company我想获得一个queryset所有的人在公司

Using使用

def persons_by_company(company_name):
    l = []
    for d in Department.objects.filter(company__name=company_name):
        for p in d.persons:
            l.append(p)
    return l

would be将是

  1. slow减缓
  2. does return a list and not a queryset (is not filterable, etc)确实返回一个列表而不是一个查询集(不可过滤等)

What would be the way to get a queryset here?在这里获取查询集的方法是什么?

In my case, I think it's quite simple with just就我而言,我认为这很简单,只需

Person.objects.filter(departement__company__id=company_id).distinct()

or with the company name:或使用公司名称:

Person.objects.filter(departement__company__name__iexact=company_name).distinct()

Your function would become:你的功能会变成:

def persons_by_company(company_name):
    return Person.objects.filter(departement__company__name__iexact=company_name).distinct()

It returns a queryset and it's faster.它返回一个QuerySet,它的速度更快。 I use iexact to avoid case sensitive.我使用iexact来避免区分大小写。

UPDATED: .distinct() Just to remove duplicate entries.更新: .distinct()只是为了删除重复的条目。

First you must have foreign key binded to your company or department首先你必须有外键绑定到你的公司或部门

class Department(models.Model):
    name = models.CharField(max_length=10)
    company = models.ForeignKeyField(to=Company, related_name="department_company_key")

class Person(models.Model):
    name = models.CharField(max_length=10)
    person_department = models.ForeignKey(
        'Department',
        related_name="person_department_key"
        on_delete=models.CASCADE,
        blank=False,
        null=False
    )

then in your function:然后在你的函数中:

def persons_by_company(company_name):
    l = []
    for d in Department.objects.filter(company__name=company_name):
        for p in d.person_department_key.all(): # You also apply some filter()
            l.append(p) # Remember This will append object  not  string or dictionary
    return l

Don't forget that related name must be unique不要忘记相关名称必须是唯一的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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