I followed suggestion from this question 但我需要query_set的一個字段名稱至今提起另一個對象的DRF改變Django模型的字段名值與外鍵
我的模型
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選項認爲是更好的方法來處理我的特定問題?謝謝!
我將不勝感激如何反正序列化相關領域,以供將來參考任何幫助傳遞給串行變化值之前建議。 –