Search code examples
djangodjango-select-related

Returning the related field using in views.py Django


I have the following code:

models.py

class Model_ItemName(models.Model):
    item_name = models.CharField(max_length = 50) # e.g. "Power Ranger"

class Model_Cart(models.Model):
    item_name = models.ForeignKey(Model_ItemName)

views.py

Model_Cart.objects.select_related("item_name").values("item_name")[0]["item_name"] # <---- Expect to return "Power Ranger"

My goal is to retrieve the value of the "item_name" (say "Power Ranger") from the Model_ItemName.

I was referring to this post for the solution, but my existing code returns the id number of that "item_name" instead. What am I missing here?


Solution

  • You can use item_name__item_name as field name (check this part of documentation for details):

    Model_Cart.objects.values("item_name__item_name")[0]["item_name__item_name"]
    

    Note you don't need select_related in this case, with values() Django will fetch item_name__item_name with one query using sql join.