0

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?

Fxs7576
  • 1,259
  • 4
  • 23
  • 31

1 Answers1

2

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.

neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100
  • 1
    You have just simplifying the existing code. Thank you very much for being a savior. Spent hours dealing with this. – Fxs7576 Jun 12 '18 at 09:31