Noyan Aziz
Noyan Aziz

Reputation: 1

Changing Year, Month, or Day in a Django model's date field using annotate

I have a Django model MyModel

class MyModel(models.Model):
"""My Model that stores date."""

    date = models.DateField()

In my API I am receiving a param, review_month I need to get all the entries in MyModel and replace their date's year value.

I have the following condition for what year to add: -> If date__month is greater than review_month the year will be current year otherwise the year will be previous year.

I need these new date fields with updated years for every entry of the MyModel queryset

MyModel.objects.annotate(
   updated_year=Case(
       When(
           Q(review_date__month__gt=review_month.month), then=previous_year),
           default=current_year,
           output_field=IntegerField(),
       ),
   )
)

This only give me year separately but I want an updated_date that has day and month of date field and this new updated year in it and must be a DateField as I need to apply sorting to it.

Upvotes: 0

Views: 173

Answers (1)

Noyan Aziz
Noyan Aziz

Reputation: 1

I have been able to solve it, so if anyone in future lands on this question here is how I did it.

MyModel.objects.annotate(
    review_day=Func(
        F('review_date'), Value('DD'), function='to_char', 
        output_field=CharField()
    ),
    review_month=Func(
        F('review_date'), Value('MM'), function='to_char',
        output_field=CharField()
    ),
    updated_year=Case(
        When(Q(review_date__month__gt=review_month.month), 
           then=previous_year,
        ),
        default=current_year,
        output_field=IntegerField(),
    ),
    review_at=Concat(
        F('updated_year'), Value('-'), F('review_month'), 
        Value('-'), F('review_day'), output_field=DateField()
    )
)

Upvotes: 0

Related Questions