1

I am working on a small project but i cant get the serializers to work

I have tried these and i am not sure what i am doing wrong. My model is a many to many throughenter image description here

    #serializers.py
    class CompanyVisitedSerializer(serializers.HyperlinkedModelSerializer):

    company_id = serializers.ReadOnlyField(source="company.id")
    company_address = serializers.ReadOnlyField(source="company.business_address")
    company_name = serializers.ReadOnlyField(source="company.business_name")
    company_address = serializers.ReadOnlyField(source="company.business_address")
    checked_in = serializers.ReadOnlyField(source="user.checked_in")
    checked_out = serializers.ReadOnlyField(source="user.checked_out")

    class Meta:
        model = CompanyUser
        fields = (
            "checked_in",
            "checked_out",
            "company_name",
            "company_address",
            "company_id",
        )


class VisitorSerializer(serializers.ModelSerializer):

    # visited = CompanySerializer(many=True)
    visited = CompanyVisitedSerializer(
        many=True,
    )
    ```

but i get this back empty {}:

    {
  "address": "192 millie road",
  "city": "singapore",
  "phone": "2066980",
  ...
  "visited": [
    {}, //i want to populate this with { company: name_of_company, checkin, checkout}
    {}
  ]
}

I have read through these:

  1. https://bitbucket.org/snippets/adautoserpa/MeLa/django-rest-framework-manytomany-through
  2. Django: Serialize a model with a many-to-many relationship with a through argument
Schnecke
  • 440
  • 1
  • 5
  • 16

1 Answers1

1

The model to which visited is pointing is a Company, not a CompanyUser. If you want to work with the CompanyUser, the relation is company_visited, so:

class VisitorSerializer(serializers.ModelSerializer):
    visited = CompanyVisitedSerializer(
        source='company_visited',
        many=True
    )
Willem Van Onsem
  • 397,926
  • 29
  • 362
  • 485