0

如果我举一个我正在研究的例子会更好。模型是

class Author(models.Model):
    id = models.IntegerField(db_column='a_id', primary_key=True)
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=20)

class Book(models.Model):
    id = models.IntegerField(db_column='b_id', primary_key=True)
    title = models.CharField(max_length=60)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

序列化器是,

class AuthorSerializer(ModelSerializer):
    class Meta:
        model = Author
        fields = ('id', 'first_name', 'last_name')


class BookSerializer(ModelSerializer):
    class Meta:
        model = Book
        fields = ('id', 'author', 'title')

视图集是,

class AuthorViewSet(NestedViewSetMixin, ModelViewSet):
    serializer_class = AuthorSerializer
    queryset = Author.objects.all()


class BookViewSet(NestedViewSetMixin, ModelViewSet):
    serializer_class = BookSerializer
    queryset = Book.objects.all()

现在以下 API 工作正常,

/authors/
/authors/{author_id}/
/authors/{author_id}/books/

但是,如果我将作者视图更改为

class AuthorViewSet(NestedViewSetMixin, ModelViewSet):
    serializer_class = AuthorSerializer
    queryset = Author.objects.all()
    lookup_field = 'first_name'

然后,以下 API 起作用

/authors/
/authors/{author_first_name}/

但以下不起作用。

/authors/{author_first_name}/books/

我知道这是因为这两个表之间的外键关系。我只是想知道如果我想保留lookup_fields 是否有任何解决方法。

谢谢

4

0 回答 0