0

I need help to fix the issue IntegrityError at /admin/gp/schprograms/add/ (1062, "Duplicate entry '65' for key 'PRIMARY'") I am trying to insert a row into a table SchProgramForStates (whenever new entry gets added into a model SchPrograms) with two columns state_id (taking it from django session) and program_id trying to take it from SchPrograms model class . It works fine when I only save SchProgram table so I feel problem is with the below code. Please help me to fix this.

@receiver(post_save, sender=SchPrograms, dispatch_uid="my_unique_identifier")
def my_callback(sender, instance, created, *args, **kwargs):
    state_id = state_id_filter #its a global variable 
    if created and not kwargs.get('raw', False):
        pfst_id = SchProgramForStates.objects.create(program_id=instance.program_id, state_id=state_id)
        pfst_id.save(force_insert=True)
Raju Singh
  • 455
  • 1
  • 6
  • 15

1 Answers1

1
if created and not kwargs.get('raw', False):
    try:
        pfst_id = SchProgramForStates.objects.create(program_id=instance.program_id, state_id=state_id)
    except:
        pass

Try with a try block and see or you can use a get or create method

if created and not kwargs.get('raw', False):
        pfst_id = SchProgramForStates.objects.get_or_create(program_id=instance.program_id, state_id=state_id)
bmons
  • 3,352
  • 2
  • 10
  • 18
  • It does not gives any error and says that `sch programs` was added successfully but it does not seem to get inserted into the database. and also I have added this line of code `pfst_id.save(force_insert=True)` into the try. – Raju Singh Dec 07 '19 at 10:52