I am working on an app that keep records of businesses and their employers Here is my model.py for Employment and Business
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)
and Business
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)
I want to get ids of all the employees with specific business id like this
employees =Employment.objects.filter(business=business, active=True)
but when I try to get id employees.id
I get error
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'
if I use get
instead of filter
suggested by this link
I still get error
MultipleObjectsReturned: get() returned more than one Employment -- it returned 5!
What should I do? Tried everything on stackoverflow
CodePudding user response:
The last error you get should give you a good hint about the issue: you are getting multiple results. If you want to see the data, you have to iterate over it:
for employee in employees:
print(employee.id)
Also, if you want only to get all the ids, there is a more performant solution:
ids = list(Employment.objects.filter(business=business, active=True).values_list('id', flat=True))