Django: Display data from other table

Question:

I’m having a hard time displaying some datas from two or three tables. So this is my code for showing all the data only from Device table.

def device(request):
    if request.method == 'GET':
        queryset = Device.objects.all()
        if queryset:
            data = {"queryset": queryset}
            return render(request, 'device/device.html', data)
        else:
            return render(request, 'device/device.html')

And I want to add some data from other table, how do I insert it here?

Asked By: krisssz

||

Answers:

Just make the queries and put the results in the render context, and refer to those in your template.

    return render(request, 'device/device.html', {
        "devices": Device.objects.all(),
        "thingabobs": Thingabob.objects.all(),
        "chili_pickles": Pickle.objects.filter(flavor="chili"),
        "plain_pickles": Pickle.objects.filter(flavor="plain"),
    })
Answered By: AKX

If the objects in the various tables have sets of fields in common and it’s these which the list view is going to display, then you can pass a mixed list of objects from different tables to be rendered. Also, in the template language, reference to a non-existent object field is not an error. {{obj.nosuchfield}} successfully renders as a null string.

So you might pass

context['vehicle_list'] = list(
    Cars.objects.filter(colour='green', available__range = [date1, date2]
  )) + list(
    Vans.objects.filter(colour='green', available__range = [date1, date2]
  ))

This is of course begging the question about whether cars and Vans should be separate tables, or Vehicles with a vehicle_type field. But sometimes, the answer is simply that its a bad choice in retrospect, but far too hard to change now.

Incidentally, properties (@property) on a model can be used to create field-name aliases for the purposes of display code, but they won’t work for queryset filtering.

Answered By: nigel222
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.