0

I've been trying hard but I can't find a solution for this, maybe you can help me:

I have 2 models: consumption and message.

The messages have a field "consumption" so I can know the consumption related.

Now I'm using DRF to get all the consumptions but I need all the messages related with them

This is my serializers.py file:

class ConsumptionSapSerializer(serializers.HyperlinkedModelSerializer):
    
    client = ClientSerializer(many=False, read_only=True, allow_null=True)
    call = CallSerializer(many=False, read_only=True, allow_null=True) 
    course = CourseSerializer(many=False, read_only=True, allow_null=True)
    provider = ProviderSerializer(many=False, read_only=True, allow_null=True)
    # messages = this is where I failed

    class Meta:
        model = Consumption
        fields = [
            "id",
            "client",
            "course",
            "provider",
            "user_code",
            "user_name",
            "access_date",
            "call",
            "speciality_code",
            "expedient",
            "action_number",
            "group_number",
            "start_date",
            "end_date",
            "billable",
            "added_time",
            "next_month",
            "status",
            "incidented",
            "messages"
        ]

class MessageSapSerializer(serializers.ModelSerializer):

     user = UserSerializer(allow_null=True)

     class Meta:
         model = Message
         fields = [
            "user",
            "date",
            "content",
            "read",
            "deleted"
         ]

I have read here Django REST Framework: adding additional field to ModelSerializer that I can make a method but I don't have the consumption ID to get all the messages related.

Any clue?

AngelQuesada
  • 387
  • 4
  • 19

1 Answers1

0

There is related_name that you can set in Message.consumption in models.py in order to call consumption.messages.

models.py

class Consumption(models.Model):
   # some fields here


class Message(models.Model):
    consumption = models.ForeignKey(Consumption, ...., related_name="messages")

P.S. Since you didn't show your models.py, I am just assuming Message.consumption is a ForeignKey.

More explanation on related_name here.

Kyell
  • 621
  • 5
  • 9