user2426362
user2426362

Reputation: 309

How to get category name of `animal` object?

I'm learning 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)

views:

def single_animal(request,id):
    animal = AniamalFile.objects.get(id=id)

How to get category name of animal object? I need display it in template also.

Upvotes: 1

Views: 147

Answers (1)

karthikr
karthikr

Reputation: 99660

In the view, you can do:

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]

You can pass this as a context variable, and access it as {{animal_category}}

Or if you want to show all the categories, just send categories in the context and in the template:

{% for cat in categories %}{{cat.name}} {% endfor %}

Alternatively,

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)

Upvotes: 2

Related Questions