簡體   English   中英

Django-使用外鍵來自其他模型的參考數據

[英]Django - Reference data from another model using a foreign key

我是Django的新手,所以請告訴我我走的路是否正確。 我有一個正在構建的Django項目,只是想問一下從一種模型檢索數據並在另一種模型中使用數據的正確Django方法是什么。

我有一個for循環,用於將必需的字段分配給變量,但是我一直在尋找一種更簡潔的解決方案,如果存在,則使用外鍵。

這是有關代碼的示例:

#MODELS

class Class1(models.Model):
    tag_number = models.CharField(max_length = 300, null = True, blank = True)
    example1 =  models.CharField(max_length = 300, null = True, blank = True)
    example2 =  models.CharField(max_length = 300, null = True, blank = True)

class Class2(models.Model):
    tag = models.ForeignKey(Class1, related_name = 'tag_foreignkey')
    example3 =  models.CharField(max_length = 300, null = True, blank = True)
    example4 =  models.CharField(max_length = 300, null = True, blank = True)



#VIEWS - This view is for Class2 but referencing fields from Class1

tag_number = str(instrumentform.cleaned_data['tag'])
query_results = Class1.objects.filter(tag_number = tag_number)
for query_result in query_results:
        example5 = query_result.example1
        example6 = query_result.example2

上面的作品,但我認為這不是Django的做事方式,並且沒有利用外鍵。

如果有人可以按正確的方向推動我,將不勝感激。

不過,仍然有百分之一百的人知道您想要什么,因為那里缺少一些信息。 對於Class1,您應該使用外鍵存儲標記來完成對Class2的操作。

對於底部的代碼,有一種簡單的方法可以實現。 (假設您使用了外鍵)

tag_number = int(instrumentform.cleaned_data['tag'])
for query_result in Class1.objects.filter(tag = tag_number).values_list('example1', 'exmaple2'):
    example5, example6 = query_result

我不確定您要在這里實現什么。 我在想PstCalc = Class1不過,如果您有

c1 = Class1()
c2 = Class2()
c3 = Class2()
and
c2.tag = c1
c3.tag = c1

使用外鍵,您將擁有:

c1.class2_set = (c2, c3) <- this would be a queryset, not a list
c2.tag = c1 => c2.tag.example1 = c1.example1

...希望我讓自己明白了:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM