@@ -1161,31 +1161,66 @@ def get_label(self, value):
11611161
11621162 def append (self , label , value , silent = False , update = None ):
11631163 if update is None :
1164- _ , created = DictionaryItem .objects .get_or_create (
1165- label = label , value = value , dictionary = self
1166- )
1167- if not created and not silent :
1168- logger .warning (
1169- "Item ({}:{}) for dictionary {} already exist" .format (
1170- label , value , self
1164+ try :
1165+ _ , created = DictionaryItem .objects .get_or_create (
1166+ label = label , value = value , dictionary = self
1167+ )
1168+ if not created and not silent :
1169+ logger .warning (
1170+ "Item ({}:{}) for dictionary {} already exist" .format (
1171+ label , value , self
1172+ )
11711173 )
1174+ except DictionaryItem .MultipleObjectsReturned :
1175+ logger .warning (
1176+ f"MultipleObjectsReturned for label={ label } , value={ value } , dictionary={ self } . Keep the first one."
11721177 )
1178+ for di in DictionaryItem .objects .filter (label = label , value = value , dictionary = self )[1 :]:
1179+ di .delete ()
11731180 elif update == "label" :
1174- DictionaryItem .objects .update_or_create (
1175- value = value ,
1176- dictionary = self ,
1177- defaults = {
1178- "label" : label ,
1179- },
1180- )
1181+ try :
1182+ DictionaryItem .objects .update_or_create (
1183+ value = value ,
1184+ dictionary = self ,
1185+ defaults = {
1186+ "label" : label ,
1187+ },
1188+ )
1189+ except DictionaryItem .MultipleObjectsReturned :
1190+ logger .warning (
1191+ f"MultipleObjectsReturned for value={ value } , dictionary={ self } . Keep the first one."
1192+ )
1193+ for di in DictionaryItem .objects .filter (value = value , dictionary = self )[1 :]:
1194+ di .delete ()
1195+ DictionaryItem .objects .update_or_create (
1196+ value = value ,
1197+ dictionary = self ,
1198+ defaults = {
1199+ "label" : label ,
1200+ },
1201+ )
11811202 elif update == "value" :
1182- DictionaryItem .objects .update_or_create (
1183- label = label ,
1184- dictionary = self ,
1185- defaults = {
1186- "value" : value ,
1187- },
1188- )
1203+ try :
1204+ DictionaryItem .objects .update_or_create (
1205+ label = label ,
1206+ dictionary = self ,
1207+ defaults = {
1208+ "value" : value ,
1209+ },
1210+ )
1211+ except DictionaryItem .MultipleObjectsReturned :
1212+ logger .warning (
1213+ f"MultipleObjectsReturned for label={ label } , dictionary={ self } . Keep the first one."
1214+ )
1215+ for di in DictionaryItem .objects .filter (label = label , dictionary = self )[1 :]:
1216+ di .delete ()
1217+ DictionaryItem .objects .update_or_create (
1218+ label = label ,
1219+ dictionary = self ,
1220+ defaults = {
1221+ "value" : value ,
1222+ },
1223+ )
11891224
11901225 def remove (self , label = None , value = None ):
11911226 if label is not None and value is not None :
0 commit comments