django static annotation

后端 未结 2 1361
走了就别回头了
走了就别回头了 2021-02-02 07:55

I want to add a static value to the results of a database query using django (so not using \'raw\' SQL)

For example, if I have an object Car with fields make, model, and

相关标签:
2条回答
  • 2021-02-02 08:07

    Update

    This solution uses soon-to-be-deprecated API. See this answer for a better way to solve this.

    Original Answer

    You can use the extra() method. Like this:

    Car.objects.all().extra(select = {'sales': 0})
    
    0 讨论(0)
  • 2021-02-02 08:22

    As of Django 1.8, annotate features Value expression:

    from django.db.models import Value, IntegerField
    
    cars= Car.objects.all().annotate(sales=Value(0, IntegerField()))
    

    Instead of IntegerField you can use all available db fields classes.

    0 讨论(0)
提交回复
热议问题