[Answered ]-Django ajax collection change

2👍

Instead of simply serializing the queryset and returning it, you could return a list containing each element in the following format:

    return [
        {
            'pk': article.pk,
            'title': article.title,
            'url': reverse('view_article', args=(article.pk,))  # Or, use article.get_absolute_url()
        }
    for article in queryset]

You can simply loop through the JSON returned, using JavaScript, and use articles[i].url in your for(var i = 0;... loop to get the URL, title, etc.

Update (re: “bad way to hardcode”):

Simply use:

serialized = json_serializer.serialize(queryset, ensure_ascii=False)
loaded = json.loads(serialized)
for row in loaded:
    row['url'] = reverse('view_article', args=(row['pk'],))
return json.dumps(loaded)

That also serves to separate the "fields" from the "url" (feels more correct).

Leave a comment