问题描述
我的查询是在MysqL中进行的,我想知道如何将其转换为ORM django,谢谢您
SELECT *,(SELECT count(*)
FROM tesisnueva.donador_desactivar ds
where ds.motivo=1 and
ds.donador_id= dd.id and
date_add(ds.fecha_desactivar,INTERVAL 90 DAY)<Now()) as cantidad
FROM tesisnueva.donador_donador dd
where dd.genero='F';
我的模型
class Donador(models.Model):
user = models.OnetoOneField(User,on_delete=models.CASCADE)
hospital = models.ForeignKey(Hospital,null=True,blank=True,on_delete=models.SET_NULL)
fecha_nacimiento = models.DateField(validators=[check_date])
direccion = models.CharField(max_length=50,null=False,blank=False)
genero = models.CharField( max_length=1,choices = GENERO,default='M')
grupo_sanguineo = models.CharField(max_length=10,choices=GRUPO_SangrE,default='A')
factor_RH = models.CharField(max_length=2,choices=FACTOR_SangrE,default='+')
telefono = models.CharField(max_length=12)
activo = models.BooleanField(default=0)
groups = models.ForeignKey(Group,on_delete=models.CASCADE)
class Desactivar(models.Model):
donador = models.ForeignKey(Donador,on_delete=models.CASCADE)
motivo= models.IntegerField()
fecha_desactivar=models.DateField()
解决方法
您可以使用.annotate(…)
[Django-doc]并使用filter=…
parameter [Django-doc]来相应地过滤相关模型:
If IO.File.Exists(filePath) Then
Using outputFile = IO.File.AppendText(filePath)
outputFile.WriteLine(Strings.Join({intNewNo(intLoop).ToString,txtName.Text,txtSurname.Text,mtbCell.Text,txtEmail.Text},","))
End Using
MessageBox.Show("Save Successful")
MessageBox.Show("Add another record","Cancel",MessageBoxButtons.OKCancel,MessageBoxIcon.Information)
txtName.Clear()
txtSurname.Clear()
mtbCell.Clear()
txtEmail.Clear()
Else
MessageBox.Show(filePath,".txt not found.",MessageBoxButtons.RetryCancel,MessageBoxIcon.Information)
End If
此查询集产生的from datetime import timedelta
from django.db.models import Q
from django.utils.timezone import now
Donador.objects.filter(genero='F').annotate(
cantidad=Count(
'desactivar',filter=Q(motivo=1,fecha_desactivar=now()-timedelta(days=90))
)
)
对象具有一个额外的属性Donador
,其中包含满足给定过滤器的相关.cantidad
对象的数量。