INSERT IGNORE in Django ORM

How do I do an INSERT IGNORE in Django ORM ?

 portal.save() # IGNORE if on DUPLICATE_KEY

It’s not clear what you’re looking to do here.

Assuming portal is an instance of an object, save is either going to update an existing row (one with an existing pk) or insert it (if the pk field is null).

update_or_create with empty defaults may be what you’re looking for.

What I got from ChatGPT :

        # Create a new Portal object and populate its fields using the data from the dictionary
        portal, created = Portal.objects.get_or_create(
            name_id=portal_data['name_id'],
            defaults={
                'name': portal_data['name'],
                'service_provider': portal_data['provider_id'],
                # Populate other fields as needed
            }
        )

        # If the portal was created, save it to the database
        if created:
            portal.save()

        cred_id = saveCredential(portal)

Well gee. To be kind, that’s redundant and unnecessary.

The get_or_create method creates the object. There is no value to having the if / save block in the code.

If you explain what the underlying objective is, we may be able to suggest an actual solution that satisfies your requirements.

I need to save the portal into the database and get the newly generated portal_id - and if it already exists I need to get the existing portal id.
I need the portal id to be used in inserting it into another related table.

The get_or_create method does that for you. No additional code is necessary.

2 Likes

I guess ChatGPT thinks that Portal.objects.get_or_create creates the object but doesn’t yet save to the database ?

ChatGPT doesn’t “think”. It emits text based on other text that it has processed to find patterns. Unfortunately, we can have no real idea as to what text it has processed to identify those patterns.

It is the untrusted sources of that generated text that cause me to strongly recommend that anyone using it always independently verify the code generated by it, and not just blindly accept it as a solution. You just never know what the side effects or vulnerabilities may be.

I agree - it can be a useful tool. But like other resources I can name (<cough>SO</cough>), it’s a starting point and not an end point.