简体   繁体   中英

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 .

For example:

data_id = 1 would return ['tab1', 'tab2', 'tab3']

data_id = 2 would return ['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.

it would look something like this. try it in your shell. 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. this appears to be only a Django question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM