2017-04-21 57 views
0

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選項認爲是更好的方法來處理我的特定問題?謝謝!

+0

我將不勝感激如何反正序列化相關領域,以供將來參考任何幫助傳遞給串行變化值之前建議。 –

回答

0
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'), 
     ) 
1

你正在接收一個json對象,你添加了它的關鍵值。

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

然後序列化並保存,一個快速的解決方案。

您還可以在模型中添加要調用的名稱。這更接近後端,也許值得深入研究。