Django 使用外键从 2 个模型读取数据并制作单个列表

Django reading data from 2 models with foreignkey and make single list

我是 django 的新手。我一直在使用 sql 进行编码,但我很难将 django orm 的 sql 知识转换为 orm 模型。 我有客户模型

class client(models.Model):
     c_id = models.AutoField(primary_key=True)
     name= models.TextField()
     age=models.IntegerField()

和地址模型

class address(models.Model):
     c_id = models.ForeignKey(client, on_delete=models.CASCADE)
     addr = models.CharField(max_lenght=20)
     city= models.CharField(max_lenght=20)

这是我的table

 ---------------------------
|   c_id|Name        | age |
 ---------------------------
|     1 | John       | 23  |
----------------------------
|     2 | Rose       | 20  |
----------------------------

------------------------------
|   c_id|addr       | city   |
------------------------------
|     1 | buspark   | florida|
------------------------------
|     2 | homesquare| florida|
------------------------------ 

如何获取列表中地址的所有客户端

查看 values() 文档

The values() method takes optional positional arguments, *fields, which specify field names to which the SELECT should be limited. If you specify the fields, each dictionary will contain only the field keys/values for the fields you specify. If you don’t specify the fields, each dictionary will contain a key and value for every field in the database table.

__ 允许获取相关数据,因此在您的情况下它可能看起来像这样

address.objects.values('c_id__c_id', 'c_id__name', 'c_id__age', 'addr', 'city')