django view检索外键的多对多关系的所有对象

时间:2017-12-09 21:30:42

标签: django django-rest-framework django-views

我有以下三种模式:

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()中写什么作为我的条件?

更新我的逻辑是:图书馆可以有很多书,一本书可以有很多作者,作者可以有很多书。

1 个答案:

答案 0 :(得分:2)

你试过了吗?

authors = Author.objects.filter(book__which_library_id=library_id).distinct()

docs many_to_many中的更多细节 (搜索文章article__headline __)