简体   繁体   English

访问 Django 模型中的 ForeignKey 实例字段

[英]Accessing ForeignKey instance fields in Django model

I'm having trouble visualizing a database query I want to run in Django.我在可视化要在 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.要获取相关字段值,您需要一个模型实例,在您的案例中为Topping类实例。 For example, you can have a custom method defined on the Topping class:例如,您可以在Topping类上定义一个自定义方法:

class Topping(models.Model):
    pizza = models.ForeignKey('pizza')

    def get_pizza_name(self):
        return self.pizza.name

self here refers to a class instance.这里的self指的是一个类实例。

Example usage:用法示例:

topping = Topping.objects.get(pk=1)
print topping.get_pizza_name()

simply:简单地:

topping = Topping.objects.get(pk=1)
print(topping.pizza.name)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM