python - 如何将两个相同的值分组并从 django、DRF 中的其他字段获取值

标签 python django django-rest-framework

我正在努力将两个相同的字段值分组并在一个响应中显示它们的相关值。

模型.py:

class Book(models.Model):
    user = models.ForeignKey(User, on_delete = models.CASCADE, null = True, blank = True)
    image = models.ImageField(default = "Nana.jpg", upload_to = 'images/', null = True, blank = True)
    title = models.CharField(max_length = 150, unique = True)
    author = models.CharField(max_length = 100)
    category = models.CharField(max_length = 100)
    description = models.TextField(max_length = 5000, null = True, blank = True)
    published_date = models.DateField(null = True, blank = True)
    language = models.CharField(max_length = 100, null = True, blank = True, default = "Not selected")
    read_book_count = models.IntegerField(default = 0)


    def __str__(self):
        return self.title

View .py:

class BookAuthors(APIView):

def get(self, request):
    author = Book.objects.all()
    serializer = AuthorSerializer(author, many = True)
    return Response(serializer.data)

序列化器.py

class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ['title', 'author']

url.py

path('library/api/authors/', views.BookAuthors.as_view()),

enter image description here

我想将作者荷马和他的两个作品放在同一个地方,不要分开。

最佳答案

您需要使用具有不同作者的查询并更改序列化程序。

View .py

class BookAuthors(APIView):

def get(self, request):
    author = Book.objects.distinct('author')
    serializer = AuthorSerializer(author, many = True)
    return Response(serializer.data)

序列化器.py

class AuthorSerializer(serializers.ModelSerializer):
    titles = serializers.SerializerMethodField()

    class Meta:
        model = Book
        fields = ['author', 'titles']

    def get_titles(self, book):
        return list(Book.objects.filter(author=book.author).values_list('title', flat=True))

输出将是这样的

[
    ...
    
    {
        "author": "author1",
         "titles": ["title1", "title2"]

    },

    ...

]

关于python - 如何将两个相同的值分组并从 django、DRF 中的其他字段获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73748239/

相关文章:

python - 直接使用用户输入查询 Django ORM 是否安全?

Django Rest Framework - 调用 "Got a ` 时出现 `Note.objects.create()' TypeError`

python - 调试 IndexError : Trivial sum generation problem

python - 模块未找到错误 : No module named 'matplotlib' even though the package is installed

django - 根据 View 传递的对象 ID 过滤表单上的外键选择选项

python - 尝试从运行在 Linux 上的 django 查询 SQL Server - 无法打开 lib '/path/to/libtdsodbc.so'

python - Django - TabularInline 没有添加按钮

python - 为使用 nodejs 调用的脚本导入 python 包

android - 从 adb logcat 捕获输出

python - Django REST Framework 上传图片 : "The submitted data was not a file"