urek mazino
urek mazino

Reputation: 165

check if object exist before saving django rest framework

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__'

Upvotes: 1

Views: 830

Answers (3)

Stark
Stark

Reputation: 61

You could try the below to snippet, which will retrive the first matched record if it's exists, then return it, or perform the original "create".

class FooViewSet(viewsets.ModelViewSet):
    serializer_class = FooSerializer
    queryset = Foo.objects.all()


    def perform_create(self, serializer: Serializer):
        a= serializer.validated_data["a"]
        b= serializer.validated_data["b"]
        # return the exists one
        if qs := self.queryset.filter(a=a, b=b):
            serializer.instance = qs.first()
            return
        super().perform_create(serializer)

Upvotes: 0

urek mazino
urek mazino

Reputation: 165

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': []},
        }

Upvotes: 0

Horatiu Jeflea
Horatiu Jeflea

Reputation: 7404

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.

Upvotes: 1

Related Questions