我正在学习django ORM。
class AnimalFile(models.Model):
filepath = models.FileField(upload_to="f")
class Food(models.Model):
main = models.ForeignKey(AnimalFile)
class Category(models.Model):
name = models.CharField(max_length=255)
food = models.ForeignKey(Food)
的观点:
def single_animal(request,id):
animal = AniamalFile.objects.get(id=id)
如何获取animal
对象的类别名称?我也需要在模板中显示它。
答案 0 :(得分:2)
在视图中,您可以执行以下操作:
def single_animal(request,id):
animal = AniamalFile.objects.get(id=id)
animal_category=None
categories = Category.objects.filter(food__main=animal)
if categories:
animal_category = categories[0]
您可以将其作为上下文变量传递,并将其作为{{animal_category}}
或者,如果您想要显示所有类别,只需在上下文和模板中发送categories
:
{% for cat in categories %}{{cat.name}} {% endfor %}
可替换地,
def single_animal(request,id):
animal = AniamalFile.objects.get(id=id)
animal_category=None
foodset = animal.food_set.all()
categories = Category.objects.filter(food__in=foodset)