0
我對Django非常陌生,但是在我們的項目中我們有一個Django後端,並且沒有其他人想要觸摸它,所以我必須對此稍作調整。 建立的模型,一切正常,但我們需要一個新的視圖,其中 我們需要關於我們的模型的基本數據,沒有參考模型(只需要外鍵ID)。我花了一天時間尋找解決方案。也許它是如此微不足道,但它並沒有在任何地方寫:)如何在Django串行器中獲取外鍵id而不是引用模型
型號:
class Row(models.Model):
row = models.IntegerField(null=True, blank=True)
height = models.TextField(null=True, blank=True)
key = models.CharField(max_length=36, unique = True)
def save(self, *args, **kwargs):
super(Row, self).save(*args, **kwargs)
class Column(models.Model):
col = models.IntegerField(null=True, blank=True)
width = models.TextField(null=True, blank=True)
key = models.CharField(max_length=36, unique = True)
def save(self, *args, **kwargs):
super(Column, self).save(*args, **kwargs)
class Product(models.Model):
key = models.CharField(max_length=36, unique = True)
text = models.TextField(null=True, blank=True)
column = models.ForeignKey(Column, db_column='column_key', to_field='key', related_name="products")
row = models.ForeignKey(Row, db_column='row_key', to_field='key', related_name="products")
merged_with = models.ForeignKey("Product", db_column='merged_with_key', to_field='key', related_name="merges", blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
updated_by = models.ForeignKey('auth.User', null=True)
現在我需要的產品列表從視圖,用JSON輸出的樣子:
{
id: 1,
key: "1746495d-8ea0-42df-9ed9-06df621ef7c5",
column_key: "<key of refrenced column>"
merged_with_key: "<key of refrenced product>"
row_key: "<key of refrenced row>"
text: "sometext"
}
在此先感謝,
喬鮑
感謝您的快速回復。結果是,我們想要的:) 但是分析在後端執行的查詢,我意識到,所有外鍵記錄都被讀取。所以現在<產品編號> * 3查詢運行而不是1.如何阻止,當我不需要引用的對象? 我知道,也許這是另一個問題... – tocsa
啊不知道,但你可以嘗試改變字段從'列','merged_with','行','column_id','merged_with_id','row_id', –
否,這是行不通的。獲取: 字段名稱'row_key'不適用於型號'產品' 我將開始另一個問題。再次感謝您的回答。這解決了原來的問題。 – tocsa