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)