[英]Django REST API return fields from ForeignKey in related model
With the following models:使用以下型号:
class Tabs(models.Model):
name = CharField(max_length=64)
def __str__(self):
return self.name
class DataLink(models.Model):
data_id = models.ForeignKey(...)
tabs_id = models.ForeignKey(Tabs, ...)
def __str__(self):
return "{} {}".format(self.data_id, self.tabs_id)
DataLink: Tabs:
id | data_id | tabs_id | id | name
------+-----------+----------- | ------+--------
1 | 1 | 1 | 1 | tab1
2 | 1 | 2 | 2 | tab2
3 | 1 | 3 | 3 | tab3
4 | 2 | 1 | 4 | tab4
5 | 2 | 4 | 5 | tab5
I need to link data between two models/tables such that for a given data_id
I can return a list of corresponding tabs, using the Tabs
table and the tabs_id
.我需要在两个模型/表之间链接数据,以便对于给定的
data_id
我可以使用Tabs
表和tabs_id
返回相应选项Tabs
列表。
For example:例如:
data_id = 1
would return ['tab1', 'tab2', 'tab3']
data_id = 1
将返回['tab1', 'tab2', 'tab3']
data_id = 2
would return ['tab1', 'tab4']
data_id = 2
将返回['tab1', 'tab4']
Is this possible?这可能吗? How?
怎么样? Is it a bad idea?
这是一个坏主意吗?
if you just want a flattened list like that given a data id, you should use values list with the key-value you want and the flat=True kwarg.如果你只想要一个像给定数据 id 的扁平列表,你应该使用带有你想要的键值和 flat=True kwarg 的值列表。
it would look something like this.它看起来像这样。 try it in your shell.
在你的 shell 中尝试一下。 https://docs.djangoproject.com/en/1.9/ref/models/querysets/#values-list
https://docs.djangoproject.com/en/1.9/ref/models/querysets/#values-list
DataLink.objects.filter(data_id=1).values_list('tabs_id',flat=True)
also, you tagged the question with django rest but has no restful context.此外,您用 django rest标记了问题,但没有宁静的上下文。 this appears to be only a Django question.
这似乎只是一个 Django 问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.