I am trying to return all the results of a many to many query (all the customers linked to a store i.e. a customer can be linked to many stores). I have the following models and serializers
class Customer(models.Model):
stores = models.ManyToManyField(Store)
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30, blank=True)
...
class Store(models.Model):
store_name = models.CharField(max_length=30, unique=True, null=True)
...
class CustomerSerializer(serializers.ModelSerializer):
stores = serializers.PrimaryKeyRelatedField(queryset=Store.objects.all(), write_only=True, many=True)
class Meta:
model = Customer
fields = ['stores', 'first_name', 'last_name', ...]
In my views, I want to get all the customers in a store and return them like this:
def return_customers(request, *args):
...
store = Store.objects.get(account__email=user)
customers = Customer.objects.filter(stores__id=store['id'])
print(customers)
json_customers = CustomerSerializer(customers).data
print(json_customers)
context = {
'customers': json_customers,
}
return Response(context, status=HTTP_200_OK)
This returns an empty object {}
print(customers) gives:
<QuerySet [<Customer: Michael>, <Customer: Naomi>, <Customer: Blessing>, <Customer: John>, <Customer: Cena>]>
print(json_customers) gives: {}
If I try to return customers
instead of json_customers
, I get error message (Type Error):
Object of type Customer is not JSON serializable
If I try json_customers = CustomerSerializer(customers[0]).data
I get only the first customer (I want all of them):
"customers": {
"id": 7,
"first_name": "Michael",
"last_name": "",
...
},
I have tried this with other models that don't have many-to-many fields and it works just fine. I have also added .values()
and .values_list()
to the end but still returns empty. SOS
CodePudding user response:
customers are multiple.
json_customers = CustomerSerializer(customers).data
change to
json_customers = CustomerSerializer(customers, many=True).data
refer to
https://www.django-rest-framework.org/api-guide/serializers/#dealing-with-multiple-objects