0

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.

Bridge
  • 191
  • 9

1 Answers1

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)
Bartosz Stasiak
  • 1,415
  • 1
  • 4
  • 9
  • 1
    Thank you so much! To be honest, the only solution I could think of was also set().difference. Glad that it's confirmed by your suggestion as well. I'll wait to see if there are any "built-in" solutions or explanations, and if there are none, I'll accept your answer. – Bridge Feb 18 '22 at 16:10