Django - 使用外键引用另一个模型的数据
我刚开始学习Django,所以如果我走错了方向,请告诉我。
我正在构建一个Django项目,想问一下,正确的Django方式是如何从一个模型中获取数据并在另一个模型中使用它。
我有一个循环,用来把需要的字段赋值给变量,但我在寻找一个更简洁的解决方案,如果有的话,希望能利用外键。
下面是相关的代码示例:
#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的标准做法,也没有充分利用外键的优势。
如果有人能给我一点指引,我将非常感激。
2 个回答
0
我不太明白你想要达到什么目的。我在想,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
...希望我说得明白 :)
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