2014-03-31 97 views
1

我是Django的新手,所以請告訴我,如果我不在正確的軌道上。 我有一個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的方式,而不是採取外鍵的優勢。

如果有人能給我一個正確的方向,將不勝感激微調。

+0

我想你可能會在Django中尋找ManyToMany關係。請查看文檔:https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/ – ruddra

回答

1

仍,百分之百不知道你想要什麼,因爲那裏有一些丟失的信息。 對於你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 
0

我不確定你想在這裏實現什麼。我想象PstCalc = 1類 不過,如果你使用外鍵具有

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 

...希望我做我自己明白:)

相關問題