【问题标题】:Django many 2 many through rest frameworkDjango many 2 many through rest framework
【发布时间】:2021-09-20 02:52:07
【问题描述】:

我正在做一个小项目,但我无法让序列化程序工作

我已经尝试过这些,但我不确定我做错了什么。我的模型是多对多 through

    #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,
    )
    ```

但我把这个返回为空{}:

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

我已经阅读了这些:

  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

【问题讨论】:

  • CompanyVisitedSerializer 继承自ModelSerializer,而不是HyperlinkedModelSerializer
  • 我试过了,我得到了相同的输出
  • 啊,但是visited 的模型是Company,而不是CompanyUser
  • 如果你想使用CompanyUser,关系是company_visitors,而不是visited

标签: django django-rest-framework


【解决方案1】:

visited 指向的模型是Company,而不是CompanyUser。如果你想使用CompanyUser,关系是company_visited,所以:

class VisitorSerializer(serializers.ModelSerializer):
    visited = CompanyVisitedSerializer(
        source='company_visited',
        many=True
    )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-05
    • 2015-05-15
    • 2021-08-07
    • 2011-09-23
    • 2018-12-15
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多