Reenu Renjith
Reenu Renjith

Reputation: 108

How to create a new object in Python Django, if it does not exist in two other classes?

There are two classes in a model- Task and TaskArchives. i need to create a new task if it does not already exist in both Task andTaskArchives. i've tried checking the DoesNotExist exception with an and clause. but it doesn't work. could someone please suggest a different method ??

for event in events:
        try:
            obj = Task.objects.get(task_id = event['id'])
            obj_archive = TaskArchive.objects.get(task_id = event['id'])

        except Task.DoesNotExist and TaskArchive.DoesNotExist:
            obj = Task.objects.create(
            task_id = event['id'],
            title = event['summary'],
            created_by = User.objects.get(email=event['creator']['email']),
            status = "upcoming",
            due_date = event['start']['dateTime']
            ) 

Thanks in advance, Reenu.

Upvotes: 3

Views: 273

Answers (1)

JRodDynamite
JRodDynamite

Reputation: 12623

You can try using the QuerySet's exists() function. It returns True if the QuerySet contains any results, and False if not.

So, for the example above I would write:

if not Task.objects.filter(task_id = event['id']).exists() and
   not TaskArchive.objects.filter(task_id = event['id']).exists:
    # no object satisfying query exists
else:
    # at least one object satisfying query exists

Upvotes: 2

Related Questions