Django在ManyToMany关系中获取相关对象

时间:2020-09-24 19:57:31

标签: django

我有一个帖子,每个帖子都包含类别列表 问题是当我收到一个帖子时,它会根据ID返回我的类别

我需要整个类别对象

帖子模型

class Post(models.Model):
    title = models.CharField(max_length=50)
    notes = models.TextField()
    image = models.ImageField(upload_to="post_image")
    time = models.CharField(max_length=50)
    steps = models.ManyToManyField(Step)
    categories = models.ManyToManyField(Category)
    created_at = models.DateTimeField(default=timezone.now)


    def __str__(self):
        return self.title


@api_view()
def get_all_posts(request):
    all_posts = Post.objects.all()
    data = JobSerializer(all_posts , many = True).data
    return Response({"data" : data})

这是回应

{
    "data": [
        {
            "id": 1,
            "title": "asdfasdsdasd",
            "notes": "asdasd",
            "image": "/post_image/117336221_134077201701397_2783193147332010898_o_oPPEef1.jpg",
            "time": "12:41",
            "created_at": "2020-09-24T01:06:58Z",
            "steps": [
                2
            ],
            "categories": [
                1
            ]
        }
    ]
}

0 个答案:

没有答案