在Django 2.1中查询模型时返回ManyToManyField ID?

时间:2019-02-06 14:23:11

标签: django django-models django-2.1

我有两个非常简单的模型:

class Person(models.Model):
    full_name = models.CharField(max_length=120)

class Event(models.Model):
    event_date = models.DateField()
    short_description = models.CharField(max_length=250)
    people_involved = models.ManyToManyField(
        Person, blank=True, related_name="people_involved"
    )

我想返回所有事件,包括people_involved

在views.py中,我有以下内容:

def alljson(request):
    events = Event.objects.values()
    return JsonResponse(list(events), safe=False)

这将返回:

[
    {
        "id": 9, 
        "event_date": "2019-01-01", 
        "short_description": "New Year's Party", 
    }, 
...
]

如何在此响应中包含people_involved ManyToManyField?

2 个答案:

答案 0 :(得分:1)

一种可能的方法,或者我认为最好的方法是使用django-restframework-serlizers link

如果您不想使用它,那么不幸的是您需要手动生成所有响应,则无法获取它们。您可以按照

def alljson(request):
    events =[] 
    for event in Event.objects.values():
         response = {}
         response['id'] = event.id
         response['short_description'] = event.short_description
         response['event_date'] = event.event_date
         response['people_involved'] = list(event.people_involved.all())
         events.append(response)


    return JsonResponse(events, safe=False)

答案 1 :(得分:1)

您可以像这样使用model_to_dict

from django.forms.models import model_to_dict

e_list = []
p_list = []
events = Event.objects.all()
for e in events:
    e_list.append(model_to_dict(e, fields=['event_date', 'short_description']))
    for p in e.people_involved.all():
        p_list.append(model_to_dict(p, fields=['full_name']))   
data = {'events': e_list, 'people_involved': p_list}
return JsonResponse(data)

如果需要,model_to_dict可以包含或排除特定字段:)

您可以像这样使用serializers

from django.core import serializers 

data = {}
events = Event.objects.all()
s_events = serializers.serialize("json", events)
data['events'] = s_events
for event in events:
    data['persons'] = serializers.serialize("json", event.people_involved.all())
return JsonResponse(data)