我有以下三种模式:
class Library(models.Model):
library_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
#This helps to print in admin interface
def __str__(self):
return u"%s" % (self.name)
class Book(models.Model):
book_id = models.AutoField(primary_key=True)
title = models.CharField(max_length=30)
# A book can have multiple authors and an author can have multiple books
author = models.ManyToManyField('Author')
# A library has many books
which_library = models.ForeignKey('Library', related_name='books', on_delete=models.CASCADE)
#This helps to print in admin interface
def __str__(self):
return u"%s" % (self.title)
class Author(models.Model):
author_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
#This helps to print in admin interface
def __str__(self):
return u"%s" % (self.name)
我想检索特定库中的所有作者。我的观点如下:
@api_view(['GET', 'POST'])
def author_list(request, library_id):
"""
List all authors in a specific library
"""
if request.method == 'GET':
authors = Author.objects.get()
serializer = AuthorSerializer(books, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = AuthorSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(
serializer.errors, status=status.HTTP_400_BAD_REQUEST)
我应该在get()中写什么作为我的条件?
更新:我的逻辑是:图书馆可以有很多书,一本书可以有很多作者,作者可以有很多书。
答案 0 :(得分:2)
authors = Author.objects.filter(book__which_library_id=library_id).distinct()
docs many_to_many中的更多细节 (搜索文章article__headline __)