Home > Software engineering >  django select related not giving expected result
django select related not giving expected result

Time:12-25

I am querying select related between two models Requirements and Badge Requirement has a related badge indicated by badge_id Models are,

        
        
        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}) 

In My view I try to join both tables and retrieve. It is,

""" 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)

The result is, to the frontend,

enter image description here

to the backend,

enter image description here

Why does it not give me both tables' values?

CodePudding user response:

Best way to achieve that is using Serializers which are the key component to deal with transforming data from models to JSON and the inverse:

To use this approach you can create the following serializers: 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__'

After that you should go to your views.py file and do the following changes:

from yourapp.serializers import RequirementSerializer


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

In this way you will have a more flexible way to add or remove fields from the serializer, and your application is also going to be more decoupled and easy to maintain.

  • Related