I have a model where a Vehicle
table has more Wheels
tables. I am trying to display in a single field the information of the vehicle and of the first wheel in the related Wheels table. I have seen that the F
function might be useful but I cannot find the correct configuration for it to work. The tables are related through another field named colour
which is declared as a foreign key in the Wheels
table.
class VehicleListView(ListView):
template_name = 'vehicle.html'
queryset = Vehicle.objects.all()
queryset = queryset.annotate(wheel1_name = F('Wheels__wheel_name'))
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
I would like the line
queryset = queryset.annotate(wheel1_name = F('Wheels__wheel_name'))
to return a list of the first wheel name for each vehicle so I can iterate through it and show it in a table.
models.py
class Vehicle(models.Model):
vehicle_id = models.AutoField(primary_key=True)
vehicle_name = models.CharField(max_length=100)
color = models.CharField(max_length=100)
class Wheels(models.Model):
wheels_id = models.AutoField(primary_key=True)
color = models.ForeignKey(Vehicle, null=True, on_delete=models.SET_NULL,
db_column='color')
wheel_name = models.CharField(max_length=100)