django选择相关未给出预期结果

cl25kdpy  于 2022-12-27  发布在  Go
关注(0)|答案(1)|浏览(98)

我正在查询两个型号要求工卡要求具有badge_id指示的相关工卡之间的相关选择型号是,

class Badge(models.Model):
            level = models.PositiveIntegerField(blank=False, unique=True)
            name = models.CharField(max_length=255, blank=False , unique=True)
            description = models.TextField(blank=True)
        
            class Meta:
                verbose_name = _("Badge")
                verbose_name_plural = _("Badges")
        
            def __str__(self):
                return self.name
        
            def get_absolute_url(self):
                return reverse("Badge_detail", kwargs={"pk": self.pk})
    
    
    """ Requirement Model for requirements """
    
    
    class Requirement(models.Model):
        number = models.PositiveIntegerField(blank=False)
        badge = models.ForeignKey(Badge, on_delete=models.CASCADE)
        name = models.CharField(max_length=255)
        description = models.TextField(blank=True)
    
        class Meta:
            verbose_name = _("Requirement")
            verbose_name_plural = _("Requirements")
    
        def __str__(self):
            return self.name
    
        def get_absolute_url(self):
            return reverse("Requirement_detail", kwargs={"pk": self.pk})

在我的视图中,我尝试连接两个表并进行检索。

""" ajax requirements in requirements table """

def get_requirements(request):

    requirements = Requirement.objects.all().select_related('badge').values()
    print(requirements)
    return JsonResponse(list(requirements), safe=False)

结果是,对于前端

后端

为什么不给予我两个表的值?

laximzn5

laximzn51#

实现这一点的最佳方法是使用Serializers,它是处理从模型到JSON的数据转换以及相反转换的关键组件:
若要使用此方法,可以创建以下序列化程序:yourapp.serializers.py

from rest_framework.serializers import ModelSerializer
from yourapp.models import Requirement, Badge

class BadgeSerializer(ModelSerializer):
    class Meta:
        model = Badge
        fields = '__all__'

class RequirementSerializer(ModelSerializer):
    badge = BadgeSerializer()

    class Meta:
        model = Requirement
        fields = '__all__'

之后,您应该转到views.py文件并进行以下更改:

from yourapp.serializers import RequirementSerializer

def get_requirements(request):
    reqs = Requirement.objects.select_related('badge')
    return JsonResponse(RequirementSerializer(reqs, many=True), safe=False)

通过这种方式,您将可以更灵活地向序列化程序添加字段或从序列化程序中删除字段,并且您的应用程序也将更加解耦和易于维护。

相关问题