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



我的目标是通过引用实体类型&实体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在数千范围内时,需要花费太多时间。

如果有任何其他方法来归档这些数据。然后请在评论中给出您的解决方案。。

用"entity_ID"字段管理外部实体的ID似乎很尴尬。为什么不对客户使用ForeignKey字段,或者在实体不总是客户的情况下,使用GenericForeignKey?

现在你正在重新发明轮子。

class Address(models.Model):
entity_type = models.CharField(null=False, max_length=255)
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL)

然后:

q = Address.objects.filter(customer in cutomers_collection)

关于ForeignKey的文档:https://docs.djangoproject.com/en/3.0/ref/models/fields/#django.db.models.ForeignKey

query_set = Address.objects.filter(
Q(entity_type='R') | Q(entity_id=1)
)
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)
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL)
address1 = models.CharField(max_length=255)
address2 = models.CharField(max_length=255)
data = Address.objects.filter(entity_type='customer', customer_id__in=[ids]).values('address1', 'address2', 'customer__name', 'customer__email')

最新更新