Conditional update_or_create with django

2019-08-21 08:03发布

问题:

Test model

class Room(models.Model):
    """
    This stores details of rooms available
    """
    name = models.CharField(
        null=False,
        blank=False,
        max_length=100,
        help_text='Enter the name of the room'
    )
    capacity = models.PositiveIntegerField(
        null=False,
        blank=False,
        help_text='Enter the number of person\'s the room can accommodate'
    )
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)

I want to update the model if it exists and its modified_at time is less than say x time otherwise just create the model. For reference here it the raw sql I want django to execute.

INSERT INTO room VALUES (1,'2018-04-30 18:15:32.96468+04:30','2018-04-30 18:15:32.96468+04:30','Room-A',30) ON CONFLICT(id) DO UPDATE SET capacity=10 WHERE room.modified_at < '2017-04-30 18:15:32.96468+04:30';

Also I would like to know if the SQL query I'have written is atomic or not

回答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})