How can I get computed elements of a table in a django queryset?

后端 未结 5 1519
野的像风
野的像风 2021-01-17 20:53

I\'m trying to use django\'s queryset API to emulate the following query:

SELECT EXTRACT(year FROM chosen_date) AS year, 
EXTRACT(month FROM chosen_date) AS          


        
5条回答
  •  北恋
    北恋 (楼主)
    2021-01-17 21:00

    You could add a property to your model definition and then do :

    @property
    def chosen_date(self):
        return self.due_date if self.due_date else self.date
    

    This assumes you can always fallback to date.If you prefer you can catch a DoesNotExist exception on due_date and then check for the second one.

    You access the property as you would anything else.

    As for the other query, I wouldn't use SQL to extract the y/m/d from the date, just use

    model_instance.chosen_date.year
    

    chosen_date should be a python date object (if you're using DateField in the ORM and this field is in a model)

提交回复
热议问题