在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python/ Django 模型定義中,如何在一個模型中獲取該模型外鍵的字段值?

Django 模型定義中,如何在一個模型中獲取該模型外鍵的字段值?

一個招標文件,可以招標同類型物品的多種型號。所以型號部分需要外鍵關(guān)聯(lián)至招標文件,并且根據(jù)招標文件的招標類型,來判斷哪些型號可以被選擇。

from django.db import models

class Bid_docu(models.Model):

PRODUCT_TYPE = (
    ('P', '打印機'),
    ('NB', '筆記本電腦'),
    ('C', '臺式電腦'),
)
bid_number = models.CharField('招標編號',max_length=13 )
title = models.CharField('標題', max_length=100 )
tenderee = models.CharField('招標人', max_length=8 )
product_type = models.CharField('設(shè)備類型', max_length=5, choices=PRODUCT_TYPE)

class Meta:
    verbose_name = '招標文件描述'
    verbose_name_plural = '招標文件描述'


def __unicode__(self):
    return self.bid_number

class Bid_docu_product(models.Model):

bid_docu = models.ForeignKey('Bid_docu', on_delete=models.CASCADE)
type = bid_docu.product_type    //這行代碼總是報錯。

def __unicode__(self):
    return self.type
    

報錯信息為:AttributeError: 'ForeignKey' object has no attribute 'product_type'這是取值時的報錯

回答
編輯回答
不舍棄
  1. 你的類命名也不規(guī)范,類命名不要有下劃線,英文單詞首字母要大寫,Bid_docu_product 建議改為 BidDocuProduct
  2. 列表項目 type = bid_docu.product_type 這一句是查找 bid_docu 變量,找不到自然報錯,按照語法可以改為 BidDocuProduct.bid_docu.product_type,但實際能否運行還要具體看。而且你這樣寫沒有任何意義,你已經(jīng)定義了外鍵,你要獲取獲取關(guān)聯(lián)表的字段,直接 BidDocuProduct.objects.first().bid_docu.product_type
2018年9月1日 18:36
編輯回答
刮刮樂

你這樣設(shè)計數(shù)據(jù)庫就數(shù)據(jù)冗余了。
Bid_docu_product沒必要保存type字段。
Bid_docu_product對象如果要獲得對應(yīng)的type,使用Bid_docu_product對象.bid_docu.product_type即可。

2017年7月2日 09:41