我有这些车型(车主可以有多辆车,一辆车可以有多个车主):
class Car(models.Model):
name = models.CharField(max_length=20)
class Owner(models.Model):
name = models.CharField(max_length=20)
class CarOwner(models.Model):
car = models.ForeignKey(Car, default = 0, on_delete=Models.CASCADE)
owner = models.ForeignKey(Owner, default = 0, on_delete=Models.CASCADE)
我想创建一个显示车主列表的模板,所以我这样做了:
def cars(request):
cars = models.Cars.objects.all()
return render(request, 'template.html', { "cars": cars })
我的template.html
就像
{% for car in cars %}
{{ car.name }} <br>
{% endfor %}
我现在如何在template.html
文件中引用每辆车的所有用户?
答案 0 :(得分:0)
CarOwner是多对多关系的直通表。你应该明确说明:
comments
现在你可以做到:
class Car(models.Model):
name = models.CharField(max_length=20)
owners = models.ManyToManyField('Owner', through='CarOwner')