Here are my models:
class Topping(models.Model):
name=models.CharField(max_length=24)
class Pizza(models.Model):
toppings=models.ManyToManyField(Topping)
Now, onto the views:
def get_pizza(request):
if request.is_ajax():
pizza_list=[]
pizza_list=Pizza.objects.all()
pizza_list_json = serializers.serialize('json', pizza_list)
return JsonResponse({'result': 'OK', 'data': {
'pizza_list': pizza_list_json,
}})
Lastly, let's take a look at the Javascript code:
function get_pizza() {
$.ajax({type: 'POST',
url: '/path/get_pizza/',
data: {
},
success: function (lista) {
if (lista.result === 'OK') {
var pizza_list_json=lista.data.pizza_list;
pizza_list = JSON.parse(pizza_list_json);
make_pizza(pizza_list);
};
}
});
};
function make_pizza() {
for (i=i; i<pizza_list.length; i++) {
var myfield=toppings;
var list_elem=pizza_list[i].fields[myfield];
};
};
The issue arises when list_elem=[1, 4]
contains object IDs instead of names like list_elem=[tomato, peperoni]
. While to_field=name
can be used with foreign keys, it doesn't work with ManyToManyField
. Attempting myfield__name
results in a myfield__name is not defined
error.
I'm wondering if there's a different approach to defining pizza_list
in the view. What could be an efficient solution to handle this situation?
Thank you.