我有一个模型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)