如何为ManyToMany关系创建端点?

时间:2017-03-13 19:08:14

标签: python django rest django-rest-framework

models.py

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时能够访问特定作者的所有出版物。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

我不确定你是否已经解决了这个问题。但这听起来很像DRF文档中特别是嵌套关系中here的序列化关系。长话短说,你的血清器中会有这些东西:

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

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

让我知道它是否有效。