I'm having trouble visualizing a database query I want to run in Django. Let's say I have a couple simple models defined:
class Pizza(models.Model):
name = models.CharField()
...
class Topping(models.Model):
pizza = models.ForeignKey('pizza')
# Get the name of pizza here
EDIT: I need to access the name in another field, not in an instance method. Is this possible?
I currently don't know how to do this. I've tried
pizza.name
But it doesn't work. Any ideas would be greatly appreciated.
To get a related field value, you need a model instance, Topping class instance in your case. For example, you can have a custom method defined on the Topping class:
class Topping(models.Model):
pizza = models.ForeignKey('pizza')
def get_pizza_name(self):
return self.pizza.name
self here refers to a class instance.
Example usage:
topping = Topping.objects.get(pk=1)
print topping.get_pizza_name()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With