Search code examples
djangodjango-modelsdjango-admindjango-admin-filters

How to get related objects from one to many relationship for display in ListView and be able to filter?


I'm looking at this tutorial from the Mozilla library. I want to create a list view in admin based on a database relationship. For example I have a Vehicle model and a statusUpdate model. Vehicle is a single instance with many statusUpdates. What I want to do is select the most recent statusUpdate (based on the dateTime field I have created) and have that data available to me in the list view.

The tutorial mentions:

class Vehicle(models.Model):

class statusUpdate(models.Model):
    vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE)

Question: How could I do a list view with model relationships and be able to filter by fields on the child relationship and pass to the view?


Solution

  • Here's what I wanted in a Class Based View (CBV), my explanation of my issue was not very clear.

    def get_context_data(self, **kwargs):
    

    get_context_data is a way to get data that is not normally apart of a generic view. Vehicle is already provided to the View because its the model defined for it, if you wanted to pass objects from a different model you would need to provide a new context, get_context_data is the way to do this. statusUpdate is a model with a foreign key to Vehicle. Full example below.

    class VehicleDetail(generic.DetailView):
        model = Vehicle
        template_name = 'fleetdb/detail.html'
    
    
        def get_context_data(self, **kwargs):
            # Call the base implementation first to get a context
            context = super(VehicleDetail, self).get_context_data(**kwargs)
            context['updates'] = statusUpdate.objects.filter(vehicle_id=1).order_by('-dateTime')[:5]
            return context