1

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

3 Answers 3

1
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.

Sign up to request clarification or add additional context in comments.

1 Comment

it is not working in rest framework that what i have tested @Horatiu Jeflea
0

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.