Alexev
Alexev

Reputation: 157

Django models, How to retrieve a property of a foreign key object

I have a class like this

class Product(models.Model):
    name = models.CharField()

another class

class Properties(models.Model):

    description = models.CharField()
    product =  models.ForeignKey(Product)

in the str function of the properties class I want to use the object product and its atributes.

 def __str__(self):
    p = Product.objects.get(Product)
    return p.name

Somehow it doesnt work,

If I just return the 'Product' it shows so it is the object itself, how can I access the atributes then?

Upvotes: 0

Views: 371

Answers (1)

Gocht
Gocht

Reputation: 10256

As @2ps says in comments:

def __str__(self):
    return self.product.name

See docs.

Upvotes: 1

Related Questions