1

I have three model Pesticide, Disease and Instruction what i want is to get all disease with relation to pesticide which relate to instruction model

class Disease(models.Model):
    name = models.CharField(max_length=100)
    def __str__(self):
        return self.name

class Pesticide(models.Model):
    name = models.CharField(max_length=50)
    def __str__(self):
        return self.name


class Treatment(models.Model):
    disease = models.ForeignKey(Disease, related_name='treatments', on_delete=models.DO_NOTHING)
    pesticide = models.ForeignKey(Pesticide, related_name='treatments', on_delete=models.DO_NOTHING)

    def __str__(self):
        return self.instruction

and serializer

class PesticideSerializer(serializers.ModelSerializer):
   
    class Meta:
        model = Pesticide
        fields = ('id', 'name')

class DiseaseSerializer(serializers.ModelSerializer):
    pesticides = PesticideSerializer(source='treatment_set', read_only=True)
    class Meta:
        model = Disease
        fields = [

            'id',
            'name',
            'pesticides',
           
        ]

My problem is that i can not get pesticides in django serializer

2 Answers 2

1

Use serializers.SerializerMethodField as

class DiseaseSerializer(serializers.ModelSerializer):
    pesticides = serializers.SerializerMethodField()

    def get_pesticides(self, disease):
        pesticide_qs = Pesticide.objects.filter(treatments__disease=disease)
        return PesticideSerializer(pesticide_qs, many=True).data

    class Meta:
        model = Disease
        fields = ['id', 'name', 'pesticides']
Sign up to request clarification or add additional context in comments.

2 Comments

I face another question how do i filter to get only single pesticide with instruction based on disease
better to ask a new question
0

I think changing the line pesticides = PesticideSerializer(source='treatment_set', read_only=True) in DiseaseSerializer to pesticides = PesticideSerializer(source='treatment_set', read_only=True, many=True) will solve your problem (you should add many=True because the relation type is one to many).

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.