2016-09-21 30 views
0

我有兩個問題。如果關係存在,我如何才能返回true?比如我也有帖子模型和評論模型,評論有foreginKey發佈。現在後系列化後,我想有這樣的事情Django Rest Framework返回True如果關係存在

{ 
id: 2 
content: "My first post!" 
has-comments: True 
} 

我的第二個問題是如何重新命名模型關係字段名?我們再次發佈帖子並發表評論。在評論模式我已經foregin鍵後像

post = models.ForeignKey(Post) 

現在,當我添加新的評論我送JSON數據與{職位:postIdHere}。是否有可能改變postId只在DRF不在Django模型?

我希望你能理解我:) Best Redgards, Sierran。

回答

1

我可以想出最接近的是一個自定義has_comments場(而不是has-comments)這在串行:

from rest_framework import serializers 

class YourSerializer(Either Serializer or ModelSerializer...): 
    has_comments = serializers.SerializerMethodField() 
    @staticmethod 
    def get_has_comments(instance): 
     # Choose whichever one works for you. 
     # You did not specify some model names, so I am just making stuff up. 
     return instance.post_set.exists() 
     return Comment.objects.filter(post_id=instance.id).exists() 

您可能還需要指定串行的Meta類領域。第一次運行時,框架會告訴你如何。

+0

謝謝!奇蹟般有效!只有我得到第二個問題的答案,我可以安然入睡:) – Sierran

+0

你可以[覆蓋'create()'](http://www.django-rest-framework.org/api-guide/viewsets/#marking - 在評論的視圖集中添加路由)。在文檔中非常容易。如果您遇到任何無證件問題,請告知我。 – Brian

+0

然後我可以保存postId發佈,但API仍然會返回{post:1}不postId ..我嘗試使用Charfield與源=發佈,但然後我失去了從下拉選擇相關帖子的可能性。 – Sierran

相關問題