我的目的是通过引用实体类型和实体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在数千个范围内时,要花费太多时间。
如果还有其他方法可以存档这些数据。然后,请在评论中给出您的解决方案。
query_set = Address.objects.filter(Q(entity_type ='R')| Q(entity_id = 1))