-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
時,我想要的是能夠訪問特定作者的所有出版物。我怎樣才能做到這一點?
'Publication.objects.filter(author__id =)' –
user2896976
請更具體。我在哪裏放置該代碼?我還需要添加什麼才能使其工作? – Fred
在您的API來看,你的函數可能是像'高清viewFunc(請求,AUTHOR_ID)'。您需要執行該查詢,該查詢將返回作者貢獻的所有出版物的列表。 – user2896976