Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing ForeignKey instance fields in Django model

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.

like image 337
Jon Martin Avatar asked Jan 24 '26 01:01

Jon Martin


1 Answers

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()
like image 169
alecxe Avatar answered Jan 26 '26 18:01

alecxe