Return ManyToManyField IDs when querying model in Django 2.1?

我怕爱的太早我们不能终老 提交于 2019-12-25 02:28:48

问题


I have two very simple models:

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

I want to return all events, including the people_involved.

In views.py, I have the following:

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

This returns:

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

How do I include the people_involved ManyToManyField in this response?


回答1:


You can use model_to_dict like this:

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)

with model_to_dict you an include or exclude a particular field if you want to :)

or

You can use serializers like this:

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)



回答2:


One of the possible way or i think is the best possible way to do that is to use django-restframework-serlizers link.

If you don't want to use that, then unfortunately you need to manually generate all the response, there is no way to get them. You can do this like following

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)


来源:https://stackoverflow.com/questions/54555815/return-manytomanyfield-ids-when-querying-model-in-django-2-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!