Home > Software design >  check if object exist before saving django rest framework
check if object exist before saving django rest framework

Time:02-13

When i post new data i want to check create new man object and dok object related to man objects but if man object alredy exist i want to append related dok to it any idea how to start i'm totally new to rest_framework

class Man(ListCreateAPIView):
    queryset =  Man.objects.all()
    serializer_class = ManSerial

model.py


class Man(models.Model):
    name = models.CharField(max_length=50,unique=True)
    age = models.IntegerField()
    def __str__(self):
        return self.name


class Dok(models.Model):
    man = models.ForeignKey(Man,on_delete=models.CASCADE,related_name="dok_man")
    cool =  models.CharField(max_length=400)
    def __str__(self) :
        return str(self.man)

serializer.py

class Dokserial(serializers.ModelSerializer):
    class Meta:
        model = Dok
        fields ='__all__'

class ManSerial(serializers.ModelSerializer):
    data = Dokserial(source="dok_man",many=True)
    class Meta:
        model = Man
        fields = '__all__'

CodePudding user response:

man = Man.objects.get_or_create(name=new_man_name, age=new_man_age)
Dok.objects.create(man=man, cool=new_cool)

This will select an existing man if present (with name and age attributes) or will create a new one if not.

CodePudding user response:

I do not know why or how, but this solved my problem: I edited my serializer class to

class ManSerial(serializers.ModelSerializer):
    data = Dokserial(source="dok_man",many=True)
    class Meta:
        model = Man
        fields = '__all__'
        extra_kwargs = {
            'name': {'validators': []},
        }
  • Related