gpt4 book ai didi

mysql - 如何在 DRF 中左连接模型(或)表

转载 作者:行者123 更新时间:2023-11-29 15:21:11 25 4
gpt4 key购买 nike

我有两个模型 Employee 和 AccessDr。

员工模型=>

class Employee(models.Model):
empid = models.CharField(max_length=20, unique=True)
empname = models.CharField(max_length=50)
phone = models.CharField(max_length=20, blank=True)
token = models.ForeignKey(
Company, to_field='token', on_delete=models.CASCADE)

def __str__(self):
return "%s" % (self.empid)

class Meta:
managed = True
db_table = 'employee'

AccessDr 模型=>

class AccessDr(models.Model):
empid = models.ForeignKey(
Employee, to_field='empid', on_delete=models.CASCADE)
_date = models.DateField()
_time = models.IntegerField()
device = models.CharField(max_length=5)
takey = models.CharField(max_length=3, default='00')
token = models.ForeignKey(
Company, to_field='token', on_delete=models.CASCADE)

def __str__(self):
return "%s %s" % (self.empid, self._date)

class Meta:
ordering = ['_date']
managed = True
db_table = 'tstrdoor'

我想在向 AccessDr 请求时返回对象,例如 SQL left join,示例 json=>

{
empid:'',
empname:'', <=this one from employee model
phone:'', <=this one from employee model
_date:'',
_time:'',
.
.


}

我怎样才能实现这一目标?

最佳答案

看看这个 LEFT JOIN Django ORM

也请阅读此内容 https://docs.djangoproject.com/en/2.2/topics/db/queries/#spanning-multi-valued-relationships

您可以通过打印查询来查看它如何转换为 SQL

Employes=AccessDr.objects.values('employee__empname','employee__phone')
print(Employes.query)

您是否在 View 中使用序列化器?在这种情况下,您可以创建一个序列化器字段它将把协议(protocol)数据作为一个数组,如下所示

class CustomerSerializer(serializers.ModelSerializer):
agreements = AgreementSerializer(many=True, read_only=True)


class Meta:
model = Customer
fields = [
'id',
'username',
'mail',
'fName',
'lName',
'fNameEng',
'lNameEng',
'personalId',
'phone',
'crmId', # "ID": "20995",
'agreements',
]
depth = 1

您是否在 View 中使用序列化器?在这种情况下,您可以创建序列化器字段它将把协议(protocol)数据作为一个数组,如下所示

{
"id": 985,
"username": null,
"mail": "undefined",
"fName": "Merab",
"lName": "Dasv",
"fNameEng": "Merab",
"lNameEng": "Dasv",
"personalId": "01022342346003629",
"phone": "5912324234282331",
"crmId": 1439,
"agreements": [
{
"id": 884,
"signDate": "2015-04-16",
"accountDate": "2015-05-01",
"amount": 0,
"comBalance": -1445.0,
"status": 1,
"details": [
{
"square": 32.38,
"amount": 35.0,
"object": {
"id": 578,
"object": 2,
"block": 1,
"floor": 19,
"flat": "7",
"cadastre": "05.24.04.055.01.563",
"square": 32.38,
"pCounter": 25915123146,
"wCounter": 104412312435,
"accountDate": "2015-04-01T00:00:00",
"comBalance": -1445.0,
"comDeptAmount": 1895.0,
"rentDate": null,
"active": 1,
"finaAmount": 0,
"crmId": 0
}
},

]
},

]
}

关于mysql - 如何在 DRF 中左连接模型(或)表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59368194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com