简体   繁体   中英

Django query list of characters from a Many-to-Many related Model

I am trying to get a list of names from a model that has a many-to-many relationship with my user model. Here is the model

# models.py

class AvailableTime(models.Model):
    time = models.TimeField()

class CustomUser(models.Model):
    available_times = models.ManyToManyField('AvailableTime', blank=True)

When I perform a query like this, the server returns the following list to the client

# views.py

doctor_list = User.objects.all().values('available_times__time')
return JsonResponse({'doctor_list': list(doctor_list}, status=200)

{
    "id": 30,
    "first_name": "Doctor",
    "last_name": "Test",
    "available_times__time": "9:00",
},
{
    "id": 30,
    "first_name": "Doctor",
    "last_name": "Test",
    "available_times__time": "9:00",
},

Is there a way to return a list of available_times instead of returning two separate objects?

Below is the result that I want

{
    "id": 30,
    "first_name": "Doctor",
    "last_name": "Test",
    "available_times__time": ["9:00", "9:30"]
}

Probably you can't do with queryset directly. So, you can try with a for loop:

result = list()
doctor_list = User.objects.all().prefetch_related('available_times')
for doctor in doctor_list:
   info = model_to_dict(doctor, fields=['id', 'first_name', 'last_name'])
   info['available_times'] = list(doctor.available_times.values_list('time',flat=True))
   result.append(info)
return JsonResponse({'doctor_list': result}, status=200)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM