'How to catch IntegrityError with ManyToMany add() with wrong ids?

I have two models (just for example):

class One(BaseModel):
    name = models.CharField()
    twos = models.ManyToManyField(Two)

class Two(BaseModel):
    title = models.CharField()

When I try to add a list of ids of model Two to model One with one.twos.add(*[id1, id2]) it works until I pass a wrong id, when this fails with

psycopg2.errors.ForeignKeyViolation: insert or update on table "one_twos" violates foreign key constraint "one_two_id_572a5216_fk_twos"
DETAIL:  Key (two_id)=(e2871924-5bb4-492e-b7c3-4c5ca3cc7f5e) is not present in table "twos_two".

django.db.utils.IntegrityError: insert or update on table "one_twos" violates foreign key constraint "one_two_id_572a5216_fk_twos"
DETAIL:  Key (two_id)=(e2871924-5bb4-492e-b7c3-4c5ca3cc7f5e) is not present in table "twos_two".

This does not seem to be the race condition (mentioned here Django: IntegrityError during Many To Many add()).

I need to tell the front-end that such-and-such id is not valid, but I can't catch these two IntergityErrors to re-raise my custom exception with a message and id.

Would highly appreciate any help with this.



Solution 1:[1]

Maybe not the best somution, but one thing you can try is to: Create a set of all ids in Two:

two_ids_set = set(Two.objects.all().values_list("id", flat=True))

then you can check for intersection or difference between sets. For example:

V Difference will return all invalid ids (id that are not present in table Two)

set([id1, id2]).difference(two_ids_set)

V Intersection will return all valid ids (ids that are present in table Two)

set([id1, id2]).intersection(two_ids_set)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bartosz Stasiak