如何列出具有相同外键对象的所有对象?

时间:2019-06-16 03:00:14

标签: python django

我有一个带有名称字段的Department模型,然后有一个带有Department字段的User模型,使用外键指向Department。如何在模板中列出部门中的所有用户?有没有不使用多对多的方法?

class Department(models.Model):
    name = models.CharField(max_length=64,unique=True)
    description = models.TextField(blank=True)

def __str__(self):
    return self.name

class User(AbstractUser):
    department = models.ForeignKey(Department,
    on_delete=models.CASCADE,
    blank=True,null=True)

def __str__(self):
    return self.username

2 个答案:

答案 0 :(得分:0)

User.objects.filter(department=<dept>)这将根据部门过滤详细信息。

答案 1 :(得分:0)

只要引用要获取用户的部门,就不必创建全新的查询集。

使用此models.py进行测试...

from django.db import models


class Department(models.Model):
    name = models.CharField(max_length=64, unique=True)
    description = models.TextField(blank=True, null=True)

    def __str__(self):
        return self.name


class User(models.Model):
    username = models.TextField()
    department = models.ForeignKey(
        Department,
        on_delete=models.CASCADE,
        blank=True,
        null=True,
    )

    def __str__(self):
        return self.username

此查询应该与您为名为Department的{​​{1}}实例检索用户所需的查询相同:

department

来自Django shell的示例:

department.user_set.all()

此外,如果将>>> from depts.models import Department, User >>> >>> department = Department.objects.create(name='The North Pole') >>> >>> for name in ('kungphu', 'K. Jones', 'S. Claus'): ... User.objects.create( ... username=name, ... department=department, ... ) ... <User: kungphu> <User: K. Jones> <User: S. Claus> >>> for user in department.user_set.all(): ... print(user) ... kungphu K. Jones S. Claus 添加到字段department.users,则可以使用department.user_set代替related_name='users'