Django - 使用外键模式属性

时间:2015-12-07 20:48:13

标签: python django

我有两个Django模型并通过Foreignkey元素连接,在第二个模型中我需要使用第一个模型的属性 - 例子(伪代码):

Class Category(models.Model):
      c_attribute = "Blue"

Class Object(models.Model):
      o_category = models.ForeignKey(Category)
      o_color = o_category.c_attribute

这里的关键是最后一行 - 我收到错误,说ForeignKey对象没有属性c_attribute。

由于

2 个答案:

答案 0 :(得分:0)

因为 o_category是类别的键不是类别本身
您可以通过type(o_category)检查是否不是类别!
因此,当连接到数据库时,您可以在应用程序的其他部分访问对象的相关Cateogry。例如在shell中,您可以编写:

c = Category()
c.save()
o  = Object(o_category = c, ...)  #create Object with desired params
... #some changes to o
o.save()
o.o_category.c_attribute #this will work! :)

答案 1 :(得分:0)

您可以使用+ (NSHTTPCookieStorage *)sharedCookieStorageForGroupContainerIdentifier:(NSString *)identifier NS_AVAILABLE(10_11, 9_0); ,但这也可能会给您带来错误。

to_field=''

最好的事情是在你的对象模型中创建一个函数,它会像你这样得到类别Class Object(models.Model): o_category = models.ForeignKey(Category) o_color = models.ForeignKey(Category, to_field="c_attribute")

c_attribute
相关问题