我正在为一个网站创建一个API,我有一个带有Books的表,另一个带有Hashtags(基本上是一个主题标签的目录,例如" #going")和一个中间表建立Books和Hashtags之间的多对多关系。我的模特是:
# models.py
class Books(models.Model):
id_books = models.AutoField(primary_key=True)
title = models.CharField(max_length=150)
class Hashtags(models.Model):
id_hashtags = models.AutoField(primary_key=True)
hashtag = models.CharField(max_length=150)
class Books_Hashtags(models.Model):
id_books_hashtags = models.AutoField(primary_key=True)
id_books = models.ForeignKey(Books, on_delete=models.CASCADE)
id_hashtags = models.ForeignKey(Hashtags, on_delete=models.CASCADE)
class Meta:
unique_together = ("id_books", "id_hashtags")
我希望有一个提供如下输出的API:
[
{
"id_books": 1,
"title": "The Hobbit",
"hashtags": [
{
"id_hashtags": 1,
"hashtag": "fantasy"
},
{
"id_hashtags": 2,
"hashtag": "fiction"
},
{
"id_hashtags": 3,
"hashtag": "middle earth"
},
]
}
]
为此,我使用DRF序列化上述模型,遵循我在网上找到的一些例子:
#serializers.py
from rest_framework import serializers
from app.models import Books, Books_Hashtags, Hashtags
class HashtagsSerializer(serializers.ModelSerializer):
hashtags = serializers.CharField()
class Meta:
model = Hashtags
fields = ('hashtag',)
class Books_HashtagsSerializer(serializers.ModelSerializer):
id_hashtag = HashtagsSerializer(many=True, read_only=True)
class Meta:
model = Books_Hashtags
fields = ('id_hashtags',)
class BooksSerializer(serializers.ModelSerializer):
id_books = serializers.IntegerField()
id_books_hashtags = Books_HashtagsSerializer(many=True, read_only=True)
title = serializers.CharField()
class Meta:
model = Books
fields = ('id_books', 'title', 'id_books_hashtags',)
我的观点如下:
#views.py
from ntgBackend.models import Books
from rest_framework import viewsets
from api.serializers import BooksSerializer
class BooksViewSet(viewsets.ModelViewSet):
serializer_class = BooksSerializer
queryset = Books.objects.all()
到目前为止,我已成功从API中获取以下输出:
[
{
"id_books": 1,
"title": "The Hobbit",
}
]
但是没有关于主题标签的信息,我知道它们存在于数据库中。 我使用DRF 3.8.2和MySQL DB以及Django 2.0.2。 请帮忙!
答案 0 :(得分:2)
我遇到了同样的问题,并进行了一些研究:
在models.py中,仅使用Books_Hashtagas作为中间表,修改Book模型,使其包含带有Hashtags的ManyToManyField。另外,请务必在第一本书之前声明您的Hashtag模型,以供参考
# models.py
class Books(models.Model):
id_books = models.AutoField(primary_key=True)
title = models.CharField(max_length=150)
hashtags = models.ManyToManyField(Hashtags, related_name='hashTg', through="Books_Hashtags"
在序列化程序文件中,请确保添加depth = 1以获取所需的内容,否则,您只会获得井号标签ID(仅适用于ListAPI)
#serializers.py
class BooksSerializer(serializers.ModelSerializer):
class Meta:
model = Books
#In case you want to filter out some fields:
#fields = ('field_A','field_B' )
fields = '__all__'
depth = 1
在视图中我使用泛型,因为它们可以满足我的大多数需求:
#views.py
from ntgBackend.models import Books
from rest_framework import generics
from api.serializers import BooksSerializer
class BooksViewSet(generics.ListCreateAPIView):
serializer_class = BooksSerializer
queryset = Books.objects.all()
我对此很陌生,希望对您有所帮助。除了Django(2.0.4),我使用的版本几乎与您相同。
祝你好运