1

我正在学习 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对象的类别名称?我也需要在模板中显示它。

4

1 回答 1

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)
于 2013-05-28T15:36:58.437 回答