Skip to content Skip to sidebar Skip to footer

Conditional Update_or_create With Django

Test model class Room(models.Model): ''' This stores details of rooms available ''' name = models.CharField( null=False, blank=False, max_le

Solution 1:

The following examples may work properly

1st Option

try:
    obj = Room.objects.get(
        id=id, # test with other fields if you want
    )
    if obj.modified_at < DATETIME:
        obj.capacity = 10
        obj.save()
    else:
        obj = Room.objects.create(
            # fields attributes
        )
except Room.DoesNotExist:
    obj = Room.objects.create(
        # fields attributes
    )

2nd Option

or you can do so with Conditional Expression of django

from django.db.models import F, Case, When
import datetime

your_date = datetime.datetime.now()
condition=Case(When(modified_at__lt=your_date,then=10),default=F('capacity'))
  • We check whether modified_at is less than your_date
  • then the value of this condition is 10,
  • else, we keep the same value of the field with F('capacity')

rest of the code

Room.objects.update_or_create(name='new_name',
           defaults={'name':'new_name','capacity':conditition})

Post a Comment for "Conditional Update_or_create With Django"