如何为多人关系创建端点?

2024-03-28 17:13:23 发布

您现在位置:Python中文网/ 问答频道 /正文

型号.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)

序列化程序.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')

网址.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'))
]

视图.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时,我想要的是能够访问特定作者的所有出版物。我该怎么做?你知道吗


Tags: namepyapitrueurlmodelslengthmax
1条回答
网友
1楼 · 发布于 2024-03-28 17:13:23

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

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

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

让我知道它是否有效。你知道吗

相关问题 更多 >