How to add extra fields to Django Queryset

时间:2018-07-25 05:02:08

标签: django django-queryset

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?

3 个答案:

答案 0 :(得分:2)

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`

答案 1 :(得分:0)

you must add some field in model.

when in your code add some attribute to model instance like :

q.due_date = '06/16'

this attribute added to instance and no where stored. so when you fetch instance from database instance has not field/attribute named due_date

答案 2 :(得分:0)

当您两次遍历一个查询集时,您基本上是在第二次查询数据库,而在第一个循环中丢失了更改。您可以使用list()关键字(例如

)强制评估查询集
qs = list(Company.objects.filter(entity=PA))