【问题标题】:DRF changing field name values of django models with foreign keysDRF 使用外键更改 django 模型的字段名称值
【发布时间】:2017-09-17 23:45:03
【问题描述】:

I followed suggestion from this question 但我需要将 query_set 的一个字段命名为另一个对象的日期字段

我的模型是

class Choice(models.Model):
    question = models.ForeignKey(Question, related_name='choice', on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text


class ChoiceWithTime(models.Model):
    choiceTime = models.ForeignKey(Choice,related_name='choiceTime', on_delete=models.CASCADE)
    choice_date=models.DateField()

我的看法

class QuestionChoicesViewSet(viewsets.ModelViewSet):
    queryset = Choice.objects.all()
    serializer_class = ChoiceDateSerializer

    def get_queryset(self):
        return Choice.objects.values('choiceTime__choice_date','choice_text').annotate(
            total_votes=Count('choiceTime__choice_date'),
        )

我需要统计特定日期的提交次数

我不知道如何命名 choiceTime__choice_date 序列化程序识别查询集中的字段

class ChoiceDateSerializer(serializers.ModelSerializer):
    choiceTime__choice_date  = serializers.DateTimeField()
    total_votes = serializers.IntegerField()

    class Meta:
        model = Choice
        fields = ('id', 'choice_text','total_votes','choiceTime__choice_date')

我收到

{
    "choice_text": "ant tower",
    "total_votes": 3,
    "choiceTime__choice_date": "2017-04-20"
}

但我想收到

{
    "choice_text": "ant tower",
    "total_votes": 3,
    "choice_date": "2017-04-20"
}

尝试了不同的选项,但没有成功。绝对我错过了重点。 就我的目的而言,它正在工作,但我想要编写良好的 API。

2选项更改时间提交模型?

class ChoiceWithTime(models.Model):
    choiceTime = models.ForeignKey(Choice,related_name='choiceTime', on_delete=models.CASCADE)
    choice_date=models.DateField()
    coutner = models.IntegerField(default=0)

2 选项是否被认为是解决我的特定问题的更好方法?谢谢!

【问题讨论】:

  • 对于如何序列化相关字段的任何帮助,我将不胜感激,以供将来参考。

标签: python django orm django-rest-framework


【解决方案1】:

您正在接收一个 json 对象,并添加它的键值。

 for vote_detail in data:
   if vote_detail.choiceTime__choice_date:
      vote_detail.choice_date=vote_detail.choiceTime__choice_date

然后序列化保存,快速解决。

您还可以在模型中添加您想要命名的名称。这更接近后端,也许值得深入研究。

【讨论】:

    【解决方案2】:
    from django.db.models import Count,F
    

    如果有人发现这个问题,这是我想出的最简单的答案。 正如在使用模型包函数传递给序列化程序更改值之前所建议的那样

    class QuestionChoicesViewSet(viewsets.ModelViewSet):
        queryset = Choice.objects.all()
        serializer_class = ChoiceDateSerializer
        def get_queryset(self):
            return Choice.objects.all().annotate(choice_date=F('choiceTime__choice_date')).values('choice_date','choice_text').annotate(
                total_votes=Count('choiceTime__choice_date'),
            )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-26
      • 2017-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多