我有一个Registration
带有外键的模型License
,该模型具有唯一的 CharField key
。
Activation
对于某些注册集,如果存在具有该许可证密钥的记录,我需要获取一个布尔值。Activation
然而,和Registration
/之间没有外键关系License
。
我可以像这样在python中做到这一点:
regis = Registration.objects.filter(...).select_related("license")
keys = regis.values_list("license__key", flat=True)
activated_keys = ActivationRecord.objects.filter(licensekey__in=keys, action="OK").values_list("licensekey", flat=True)
for r in regis:
r._was_activated = r.free_license.key in activated_keys
但是在想这应该可以通过一个extra()
电话来实现。只是我的sql技能还不够好。
我想出的是:
Registration.objects.filter(...).extra(
select={"was_activated":"SELECT EXISTS(select * FROM `activation_activationrecord`, `license_license`
where `license_license`.`license_key`=`activation_activationrecord`.`licensekey` AND `activation_activationrecord`.`action` = 'OK')"})
但r.was_activated
始终1
适用于任何记录,无论是否激活。
更新:这里是表格的相关部分:
mysql> Describe activation_activationrecord;
+-----------------+---------------+------+-----+---------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+---------------+------+-----+---------------------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| licensekey | varchar(250) | YES | MUL | NULL | |
| action | varchar(100) | NO | MUL | NULL | |
+-----------------+---------------+------+-----+---------------------+----------------+
mysql> Describe license_license;
+----------------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| license_key | varchar(255) | NO | | NULL | |
+----------------------------+--------------+------+-----+---------+----------------+
mysql> Describe registration_registration;
+--------------------------------------------+------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------------------------------+------------+------+-----+---------+----------------+
| registration_id | int(11) | NO | PRI | NULL | auto_increment |
| license_id | int(11) | NO | UNI | NULL | |
+--------------------------------------------+------------+------+-----+---------+----------------+
更新2:相关型号:
class Registration(models.Model):
id = models.AutoField(db_column="registration_id", primary_key=True)
license = models.OneToOneField(License,
related_name='registration',
default=False,
blank=False)
class License(models.Model):
key = models.CharField(db_column="license_key", max_length= 255)
class ActivationRecord(models.Model):
licensekey = models.CharField(max_length=250, null=True, db_index=True)