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)
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)