2017-03-13 70 views
-1

models.py如何爲ManyToMany關係創建端點?

class Author(models.Model): 
    first_name = models.CharField(max_length=30) 
    last_name = models.CharField(max_length=30) 
    email = models.EmailField(blank=True) 

class Publication(models.Model): 
    title = models.CharField(max_length=200) 
    pub_date = models.DateField(null=True, blank=True) 
    author = models.ManyToManyField(Author) 

serializers.py

class AuthorSerializer(serializers.HyperlinkedModelSerializer): 
    class Meta: 
     model = Author 
     fields = ('first_name', 'last_name', 'email') 

class PublicationSerializer(serializers.HyperlinkedModelSerializer): 
    class Meta: 
     model = Publication 
     fields = ('title', 'pub_date', 'author') 

urls.py

router = routers.DefaultRouter() 
router.register(r'authors', views.AuthorViewSet) 
router.register(r'publications', views.PublicationViewSet) 

urlpatterns = [ 
    url(r'^$', views.index, name='index'), 
    url(r'^api/', include(router.urls)), 
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) 
] 

views.py

class AuthorViewSet(viewsets.ModelViewSet): 
    queryset = Author.objects.all().order_by('-first_name') 
    serializer_class = AuthorSerializer 

class PublicationViewSet(viewsets.ModelViewSet): 
    queryset = Publication.objects.all() 
    serializer_class = PublicationSerializer 

我想

正如你看到的是什麼,我的兩個模型(作者出版)與一個多對多的關係連接。當我去api/authors/[id]/publications時,我想要的是能夠訪問特定作者的所有出版物。我怎樣才能做到這一點?

+0

'Publication.objects.filter(author__id = )' – user2896976

+0

請更具體。我在哪裏放置該代碼?我還需要添加什麼才能使其工作? – Fred

+0

在您的API來看,你的函數可能是像'高清viewFunc(請求,AUTHOR_ID)'。您需要執行該查詢,該查詢將返回作者貢獻的所有出版物的列表。 – user2896976

回答

0

林不知道,如果你還沒有解決了這個。但是這聽起來很像序列化關係,在DRF文檔中找到here特別是嵌套關係。長話短說,你會在你的系列化器中沿着這些方向發展:

class AuthorSerializer(serializers.HyperLinkedSerializer): 
    publications = PublicationSerializer(many=True, read_only=True) 

    class Meta: 
     model = Author 
     fields = ('...', 'publications',) 

讓我知道它是否有效。