Django中的自定义ORM。基于实体ID和实体类型

问题描述 投票:0回答:1

我的目的是通过引用实体类型和实体ID从不同的模型中检索数据。

示例:我有客户模型和地址模型

from django.db import models

class Customer(models.Model):
    name = models.CharField(null=False, blank=False, max_length=255)
    email = models.EmailField(null=False, blank=False, unique=True)

class Address(models.Model):
    entity_type = models.CharField(null=False, max_length=255)
    entity_id = models.PositiveIntegerField(null=False)
    address1 = models.CharField(max_length=255)
    address2 = models.CharField(max_length=255)

现在我使用原始查询

cursor.execute("SELECT * FROM customers AS cust 
     INNER JOIN addresses AS addrs ON 
     (cust.id = addrs.entity_id AND 'customer' = addrs.entity_type) 
     WHERE cust.id IN (%s)", [ids])

但是这不是很好的解决方案。 id在数千个范围内时,要花费太多时间。

如果还有其他方法可以存档这些数据。然后,请在评论中给出您的解决方案。

django database postgresql django-models django-orm
1个回答
0
投票

query_set = Address.objects.filter(Q(entity_type ='R')| Q(entity_id = 1))

© www.soinside.com 2019 - 2024. All rights reserved.