So, I'm using the Django update_or_create API to build my form data. It works fine...but, once built, I need a way to check to see what profiles were actually updated or if they were created for the first time?
Just an example:
for people in peoples:
people, updated = People.objects.update_or_create(
id=people.person_id,
defaults={
'first_name': people.first_name,
}
)
Filtering queryset:
people = People.objects.filter(
id__in=whatever,
)
But, now, I'm trying to filter the queryset by created or updated...but don't see an API for that (e.g., a fitler of sorts)
So, I would like to do something like:
updated = Person.objects.filter(updated=True, created_for_first_time=False)
and then I can write something like
if updated:
do this
else:
do this
Basically, I just want to check if a profile was updated or created for the first time.
As you have shown in your question, the update_or_create
method returns a tuple (obj, created)
, where obj
in the object, and created
is a boolean showing whether a new object was created.
You could check the value of the boolean field, and create a list to store the ids of the newly created objects
new_objects = []
for people in peoples:
obj, created = People.objects.update_or_create(...)
if created:
new_objects.append(obj.id)
You can then filter using that list:
new_people = People.objects.filter(id__in=new_objects)
existing_people = People.objects.exclude(id__in=new_objects)