我在 Django 中收到多个查询集错误

I am getting Multiple Query set Errors in Django

我正在开发一款记录企业及其雇主的应用程序 这是我的 model.py 就业和商业

class Employment(BaseModel):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    business = models.ForeignKey(Business, on_delete=models.CASCADE)
    role = models.CharField(
        max_length=128, choices=EMPLOYEE_ROLE_CHOICES, default="EMPLOYEE")
    deduction_amount = models.IntegerField(default=0, blank=True)
    email = models.CharField(max_length=1028)
    active = models.BooleanField(default=True)
    account_balance = models.PositiveIntegerField(default=0)

和商业

class Business(BaseModel):
    name = models.CharField(max_length=255)
    tax_id = models.CharField(max_length=255, blank=True, default="")
    contact_email = models.CharField(max_length=255)
    contact_first_name = models.CharField(max_length=255)
    contact_last_name = models.CharField(max_length=255)
    contact_phone = models.CharField(max_length=255, blank=True, default="")
    description = models.TextField(blank=True, default="")
    address = models.ForeignKey(
        Address, null=True, blank=True, on_delete=models.CASCADE)
    image = models.ForeignKey("main.Image", null=True,
                              blank=True, on_delete=models.CASCADE)
    json_data = JSONField(blank=True, default=dict)

我想像这样获取具有特定业务 ID 的所有员工的 ID

employees =Employment.objects.filter(business=business, active=True)

但是当我尝试获取 id employees.id 我收到错误

In [44]: employees =Employment.objects.filter(business=b, active=True)

In [45]: employees.id

<ipython-input-45-5232553f9273> in <module>
----> 1 employees.id

AttributeError: 'QuerySet' object has no attribute 'id'

如果我使用 get 而不是 this link 建议的 filter 我仍然收到错误

MultipleObjectsReturned: get() returned more than one Employment -- it returned 5!

我该怎么办?在 Whosebug

上尝试了一切

你得到的最后一个错误应该给你一个很好的提示:你得到了多个结果。如果要查看数据,则必须对其进行迭代:

for employee in employees:
    print(employee.id)

此外,如果您只想获取所有 ID,还有一个更高效的解决方案:

ids = list(Employment.objects.filter(business=business, active=True).values_list('id', flat=True))