Home > Enterprise >  Updating Django ORM with filter is updating unexpected fields
Updating Django ORM with filter is updating unexpected fields

Time:08-18

I have a very simple DjangoRestFramework api_view where i am grabbing an id and filtering a queryset by that id and a start date greater than today.

My Model is pretty simple, it has a patient (FK), is_cancelled (boolean), start (Datetime) and end (Datetime).

The issue is that when i run the below update, it is setting the start date to the date and time that i run this view.

@api_view(['POST'])
def BookingCancelAppointmentsView(request):
    if request.method == 'POST':
        patient_id = request.data
        today = date.today()
        bookings = Booking.objects.filter(patient=patient_id, start__gte=today).update(is_cancelled=True)
    return Response({'message': 'Appointments cancelled'})

so for example, if find an entry that is greater than today for that patient_id, it does update the "is_cancelled" field for the correct record but it is setting the Start datetime from whatever datetime i had in there originally to the date.today() value even though i am only updating the "is_cancelled" field.

Does anyone have any idea why it would touch the "start" field at all and how i might get around this issue?

Software Versions:

  • Python Version: 3.10.5
  • Django Version: 3.2.15
  • Django Rest Framework Version: 3.13.1

CodePudding user response:

Try to check your Booking model. It might be because you set auto_now=True on the start field.

Ex.

class Booking(models.Model):
    is_cancelled = models.BooleanField()
    start = models.DateTimeField(auto_now=True)

If auto_now=True the field will be automatically set to now every time the object is saved

CodePudding user response:

If you just need to set the time fields at the time of object creation. You can pass auto_now_add=True, instead of auto_now=True.
The auto_now will update the field every time the save method is called.

class Booking:
    <...other fields here...>
    start = models.DateTimeField(auto_now_add=True)
    end = models.DateTimeField(auto_now_add=True)

Alternative you can use bulk operations to save data to models. On Bulk operations these fields will not be updated. Though this is not a suggested approach, this is just a hack if you don't want to change your models due to some reasons.

  • Related