I want to insert only new data into my database. In case, the data with the same primary key is already in the database, I want to ignore it and not raise an exception. However, the default ModelSerializer's create function seems to raise and exception if the value already exists in the table. So, I am trying to solve this problem by overriding the ModelSerializer's create() function.
Here's my code:
serializers.py
class UsrPlaceMapSerializer(serializers.ModelSerializer):
class Meta:
model = UsrPlaceMap
fields = '__all__'
def create(self, validated_data):
place_id = validated_data.get("ggl_plc_id")
place_map = UsrPlaceMap.objects.filter(ggl_plc_id=place_id)
print("USRMAP INIT")
if place_map is not None:
print("USRMAP NOT NONE")
return place_map
place_map = UsrPlaceMap.objects.create(ggl_plc_id=place_id, state=validated_data.get("state"),
cty_nm=validated_data.get("cty_nm"), cntry=validated_data.get("cntry"))
print("USRMAP CREATED")
return place_map
models.py
class UsrPlaceMap(models.Model):
cty_nm = models.CharField(max_length=500)
state = models.CharField(max_length=200, blank=True, null=True)
cntry = models.CharField(max_length=500)
ggl_plc_id = models.CharField(primary_key=True, max_length=500)
class Meta:
managed = False
db_table = 'usr_place_map'
and I am calling the seralizer instance's save method using this:
instance = UsrPlaceMapSerializer(data=data, many=True)
if instance.is_valid():
instance.save()
The values get saved if I submit new values. However, I get an error if I try to submit values already in the table:
{
"ggl_plc_id": [
"usr place map with this ggl plc id already exists."
]
}
}
The print statements on the overriddent create() don't print anything either. So, I am guessing that the overridden method is not running at all. What am I doing wrong or what would be the proper way to tackle this problem? Thank you.