Reputation: 1201
I have problem on using update_or_create method in django I have following model
class Search(BaseModel):
booking_id = models.IntegerField(db_index=True, unique=True)
trip_type = models.CharField(max_length=20, choices=trip_choice)
flight_date = models.DateField()
return_date = models.DateField(null=True, blank=True)
And I tried creating if not exists or update existing value but I am getting integrity error:
duplicate key value violates unique constraint "flight_search_booking_id_key" DETAIL: Key (booking_id)=(4) already exists.
Here is how I tried saving.
def _save_to_db(self):
# 14. check if booking id exists previously if exists raise error
defaults = {'booking_id': 4}
flight_data, _created = Search.objects.update_or_create(
booking_id=self._flight_data.get('booking_id'),
trip_type=self._query_params.get('flight_type'),
flight_date=self._query_params.get('departure_date'),
defaults=defaults
)
flight_data.save()
I learned default should be provided so I did that too but I am getting error.
Upvotes: 1
Views: 942
Reputation: 571
def _save_to_db(self):
# 14. check if booking id exists previously if exists raise error
defaults = {'booking_id': 4}
flight_data, _created = Search.objects.update_or_create(
booking_id=self._flight_data.get('booking_id',defaults.get("booking_id")),
trip_type=self._query_params.get('flight_type'),
flight_date=self._query_params.get('departure_date')
)
flight_data.save()
Try it.
Upvotes: 1
Reputation: 2058
If your intent is to update the booking with booking_id == 4
, then I think this is the correct approach:
def _save_to_db(self):
# 14. check if booking id exists previously if exists raise error
defaults = {
'trip_type': self._query_params.get('flight_type'),
'flight_date': self._query_params.get('departure_date'),
'booking_id': 4,
}
flight_data, _created = Search.objects.update_or_create(
booking_id=self._flight_data.get('booking_id'),
defaults=defaults
)
flight_data.save()
That will update the values of trip_type and flight_date in the Search
object with booking_id=4
, or create such a Search
object otherwise.
Take a look at the django documentation which specifies what the approximate equivalent code is that doesn't use update_or_create: https://docs.djangoproject.com/en/3.2/ref/models/querysets/#django.db.models.query.QuerySet.update_or_create
Upvotes: 1