Shahmeer Khalid
Shahmeer Khalid

Reputation: 21

Backward lookup in Django

Following are my model classes.

class Categories(models.Model):
  name= models.CharField(max_length=255, unique=True)


class Values(models.Model):
  category = models.ForeignKey(Categories)
  language = models.CharField(max_length=7)
  category_name = models.CharField(max_length=50)

Lets say I have already got list of Values. Now I want to get name of the Category to which this Value object is related to. How can I do that ? Will appreciate your help.

Upvotes: 2

Views: 34

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477684

You can fetch that with:

myValue.category.name # name of myValue

If you are fetching multiple Value objects, then you can use .select_related(..) [Django-doc] to boost retrieving the Category objects:

values = Value.objects.select_related('category')
for value in values:
    print(value.category.name)

Note: normally a Django model is given a singular name, so Value instead of Values, and Category instead of Categories.

Upvotes: 2

Related Questions