I'd like to add some extra fields to my queryset.
models.py
class Company(models.Model):
ENTITY_CHOICES = ( ('CO', 'Corporation'),('PR','Proprietor'),('PA','Partnership'),('NO','Nonprofit'))
legal_name = models.CharField(max_length=120, blank=True)
entity = models.CharField(max_length=1, null=True, choices=ENTITY_CHOICES, default='CO')
client = models.ForeignKey(Clients, models.SET_NULL, blank=True, null=True)
views.py
qs = Company.objects.filter(entity=PA)
for q in qs:
q.due_date = '06/15'
for q in qs:
print('due_date',q.due_date)
It was successful in many times. But the result is not stable and I happen to see errors as follows,
Exception Type: AttributeError
Exception Value:
'Companies' object has no attribute 'due_date'
Is there any better way to add extra attribute to querysets?
You could use property
as
class Company(models.Model):
ENTITY_CHOICES = (('CO', 'Corporation'), ('PR', 'Proprietor'), ('PA', 'Partnership'), ('NO', 'Nonprofit'))
legal_name = models.CharField(max_length=120, blank=True)
entity = models.CharField(max_length=1, null=True, choices=ENTITY_CHOICES, default='CO')
client = models.ForeignKey(Clients, models.SET_NULL, blank=True, null=True)
@property
def due_date(self):
# your logic for due date
return due_date
Example:
from datetime import timedelta
class Company(models.Model):
# your fields
start_date = models.DateField()
@property
def due_date(self):
# due date is calcualted 10 days from start_date
return self.start_date + timedelta(days=10)
Accessing due_date
,
company_obj = Company.objects.get(id=some_id)
company_obj.due_date # you will get `due_date`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With