Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django "update_or_create" API: how to filter objects by created or updated?

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.

like image 652
Michael Sebastian Avatar asked Jan 05 '23 20:01

Michael Sebastian


2 Answers

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)
like image 94
Alasdair Avatar answered Jan 08 '23 10:01

Alasdair


When you call update_or_create:

person, created = People.objects.update_or_create(...)

the created return value will be True if the record was freshly created, or False if it was an existing record that got updated. If you need to act on this bit of information, it would be best do do it right here, while you have access to it.

If you need to do it later, the only way I can think of is to design a schema that supports it, i.e. have create_date and last_modify_date fields, and if those two fields are equal, you know the record has not been modified since it was created.

like image 20
John Gordon Avatar answered Jan 08 '23 11:01

John Gordon