【发布时间】:2021-06-17 16:35:23
【问题描述】:
我有三个模型:Brand、Log 和 Abstract MWModel。
class Log(models.Model):
app = models.CharField(max_length=20, choices=get_modules())
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
method = models.CharField(max_length=8, choices=HTTP_METHODS)
url = models.TextField()
body = models.TextField(null=True)
code = models.IntegerField()
message = models.TextField(null=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.created_at.isoformat()
class MWModel(models.Model):
log = GenericRelation(Log)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Brand(MWModel):
name = models.CharField(max_length=50)
status = models.BooleanField(default=True)
def __str__(self):
return self.name
如何获取为每个品牌创建的最后一条日志记录的code字段?
我有这个
Brand.objects.filter(
merchant=account.merchant,
identity__app=F('merchant__erp')
).annotate(
log__last__created_at=Max('log__created_at'),
log__last__code=Log.objects.filter(
content_type__model=Brand._meta.model_name,
object_id=OuterRef('pk')
).order_by('-created_at').values('code')[:1]
).values('pk', 'name', 'log__last__created_at', 'log__last__code')
我需要这样的东西
Brand.objects.filter(
merchant=account.merchant,
identity__app=F('merchant__erp')
).annotate(
log__last__created_at=Max('log__created_at'),
log__last__code=F('log__code', filter=Q('log__created_at'=F('log__last__created_at')))
).values('pk', 'name', 'log__last__created_at', 'log__last__code')
但我还没有找到类似的代码。
非常感谢您的帮助。谢谢。
【问题讨论】:
标签: python django django-models django-queryset