【问题标题】:How to join models in Python djangorestframework如何在 Python djangorestframework 中加入模型
【发布时间】:2017-11-10 18:45:01
【问题描述】:

我正在尝试在 django-rest-framework 中联合两个模型。 我的代码没有抛出任何错误,但也没有显示需要加入的其他模型字段。

下面是我的代码sn-p:

序列化器:

class CompaniesSerializer(serializers.ModelSerializer):
    class Meta:
        model = Companies
        fields = ('id', 'title', 'category')

class JobhistorySerializer(serializers.ModelSerializer):
    companies = CompaniesSerializer(many=True,read_only=True)
    class Meta:
        model = Jobhistory
        fields = ('id', 'title', 'company_id', 'companies')

查看

class UserJobs(generics.ListAPIView):
    serializer_class = JobhistorySerializer()

    def get_queryset(self):
        user_id = self.kwargs['user_id']
        data = Jobhistory.objects.filter(user_id=user_id)
        return data

型号:

class Companies(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=100, blank=True, default='')
    category = models.CharField(max_length=30, blank=True, default='')
    created = models.DateTimeField(auto_now_add=True)

class Meta:
   ordering = ('created',)

def save(self, *args, **kwargs):
    title = self.title or False
    category = self.category or False
    super(Companies, self).save(*args, **kwargs)

class Jobhistory(models.Model):
    id = models.AutoField(primary_key=True)
    company_id = models.ForeignKey(Companies)
    title = models.CharField(max_length=100, blank=True, default='')
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
       ordering = ('created',)

    def save(self, *args, **kwargs):
        company_id = self.company_id or False
        title = self.title or False

    super(Jobhistory, self).save(*args, **kwargs)

提前致谢。任何帮助将不胜感激。

【问题讨论】:

  • 你能解释一下哪些字段没有显示吗? company_id 还是 companies?您还可以添加您的models.py 文件吗?
  • 我希望添加公司模型的所有字段作为响应。
  • 我明白了,看看你的models.py 文件会很有帮助。我假设Jobhistory 有一个指向Companies 的ForeignKey?
  • 添加您的 models.py 和 views.py,以获得更多说明
  • 介意您是否也可以发布您的模型?

标签: django python-3.x django-models django-rest-framework


【解决方案1】:

在你看来,你有

serializer_class = JobHistorySerializer()

去掉括号。

原因在GenericAPIView 中很明显,特别是get_serializer()get_serializer_class() 方法:

def get_serializer(self, *args, **kwargs):
    """
    Return the serializer instance that should be used for validating and
    deserializing input, and for serializing output.
    """
    serializer_class = self.get_serializer_class()
    kwargs['context'] = self.get_serializer_context()
    return serializer_class(*args, **kwargs)

def get_serializer_class(self):
    """
    Return the class to use for the serializer.
    Defaults to using `self.serializer_class`.
    You may want to override this if you need to provide different
    serializations depending on the incoming request.
    (Eg. admins get full serialization, others get basic serialization)
    """
    assert self.serializer_class is not None, (
        "'%s' should either include a `serializer_class` attribute, "
        "or override the `get_serializer_class()` method."
        % self.__class__.__name__
    )

    return self.serializer_class

正如您在get_serializer 中看到的,它使用您的视图代码中未提供的 args 和 kwargs 初始化该序列化程序类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-07
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    相关资源
    最近更新 更多