gpt4 book ai didi

django - 如何将 django 中的查询集转换为 json

转载 作者:行者123 更新时间:2023-12-04 12:25:38 25 4
gpt4 key购买 nike

我已经看到他的问题已多次回答 django < 2.xx,但对于我使用的当前版本 (2.1),我无法将我的查询集转换为 json 格式。我已经尝试过使用 django rest 框架的序列化程序,但到目前为止我能够实现的唯一用途是序列化一个模型,所以当我的查询集有来自不同模型的结果时,它不起作用。

这真的很烦人,在像 Laravel 这样的框架中,这应该非常简单,我将不胜感激。

class Medic(models.Model):
objects = models.Manager()
user_id = models.OneToOneField(User, on_delete=models.DO_NOTHING)
points = models.PositiveIntegerField(default=0)
validated = models.BooleanField(default=0)
qualification = models.PositiveIntegerField(
default=0, validators=[MaxValueValidator(10)])
referral_code = models.CharField(max_length=10)
profesional_license = models.CharField(max_length=20)

class CustomUser(AbstractUser):
# add additional fields in here
first_name2 = models.CharField(default='', max_length=20)
last_name2 = models.CharField(default='', max_length=20)
dni = models.CharField(max_length=20)
cell = models.CharField(max_length=10)
role = models.CharField(max_length=45)
city_id = models.ForeignKey(City, on_delete=models.DO_NOTHING)

和一个查询示例:
medic = Medic.objects.filter(
user_id__city_id=comercial.city_id).select_related('user_id').values()

最佳答案

我已经尝试过使用 Django rest 框架的序列化程序,您不需要 rest-framework 来序列化 QuerySet,您可以:

# This is according to your example, I, really can't imagine 
#, why you're saying you have a queryset having results from
# different models. If you're using QuerySet.union, or some similar
# feature, serialize QuerySets before join them.
from django.core.serializers import json

medic = Medic.objects.filter(
user_id__city_id=comercial.city_id).select_related('user_id')

json_serializer = json.Serializer()
json_serialized = json_serializer.serialize(medic)

关于django - 如何将 django 中的查询集转换为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54355275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com