1

models:

class Light(models.Model):
    name = models.CharField(max_length=255, default="neues Licht", null=False, blank=False)
    percentage = models.IntegerField(default=0, null=False, blank=False)

    def __str__(self):
        return self.name
    
class LightGroup(models.Model):
    name = models.CharField(max_length=255, default="neue Gruppe", null=False, blank=False)
    lights = models.ManyToManyField(Light,related_name='groups')

    def __str__(self):
        return self.name 

views:

def get(self, request, *args, **kwargs):
        lights = Light.objects.all().values()
        lights_list = list(lights)
        return JsonResponse(lights_list, safe=False) 

result:

[{"id": 2, "name": "light 1", "percentage": 3}] 

How do I include the groups in the jsonresponse?

The connection does show up when viewing groups in the admin panel. But even when I try to read from the LightGroup Model, the associated Lights do not show up.

Edit:

When try something like this:

def get(self, request, *args, **kwargs):
        obj = Light.objects.all()
        lights = obj.groups.all().values()
        lights_list = list(lights)
        return JsonResponse(lights_list, safe=False)

I get: AttributeError - 'QuerySet' object has no attribute 'groups'

edit 2: solution:

I used Manjit Kumars answer to get to the groups and was able to get the data in the form I wanted:

    def get(self, request, *args, **kwargs):
        lights_list =[]
        lights = Light.objects.all().values()

        lights_obj = Light.objects.all()
        for light_obj, light in zip(lights_obj, lights):
            light_groups = light_obj.groups.all().values()
            light["groups"] = list(light_groups)
            lights_list.append(light)
        return JsonResponse(lights_list, safe=False)

json

Nikolas
  • 15
  • 4

1 Answers1

1

Model.objects.all() returns a queryset that has all the matches objects of the model.

What you want to do is:

def get(self, request, *args, **kwargs):
    lights_list = []
    lights = Light.objects.all()
    for light in lights:
        light_groups = light.groups.all().values()
        lights_list = list(light_groups)
    return JsonResponse(lights_list, safe=False)

Alternatively, you can look into django-rest-framework and ModelViewSets which gives you alot more to do with your APIs.

Manjit Kumar
  • 1,221
  • 1
  • 19
  • 28