我目前正在准备一些日志条目为JSON序列化格式。
我试图通过Django的内置ORM,使用注释和聚合来实现这一点。
我试图在每个“日志记录项”中复制以下结构:
...
{
"count": 20,
"metric-type": "total-dataset-requests",
"access-method": "regular",
"country-counts": {
"au": 6,
"jp": 1,
"us": 13
}
}
...我目前已经根据自己的知识构建了这个queryset:
metrics = LoggedItem.objects.filter(
identifier=record['identifier'],
hit_type='investigations',
is_machine=False,
is_robot=False
).values(
'identifier', 'country'
).annotate(
count=models.Count('identifier'),
metric_type=models.Value("total-dataset-requests", output_field=models.CharField()),
access_method=models.Value("regular", output_field=models.CharField())
)这给了我一个<Queryset []>,如下所示:
<QuerySet [{'identifier': '10.80519/954e-4db4', 'country': 'fr', 'count': 1, 'metric_type': 'total-dataset-requests', 'access_method': 'regular'}, {'identifier': '10.80519/954e-4db4', 'country': 'gb', 'count': 5, 'metric_type': 'total-dataset-requests', 'access_method': 'regular'}]>如您所见,我拥有模拟上述数据结构所需的所有数据。但以一种视觉模糊的形式..。我可以使用values_list()或迭代器()来清除这个问题,但是我想通过ORM在数据库层完成大部分的繁重工作。
所以我想我的问题是,如何复制JSON结构中显示的聚合子作为ORM查询.?
FYI:从LogItem中了解完整的models.py可能是有用的:
class LogItem(models.Model):
....
id = models.AutoField(_('ID'), primary_key=True)
session_id = models.TextField(_('Session ID'), default='')
doubleclick_id = models.TextField(_('Doubleclick ID'), default='')
event = models.DateTimeField(_('Event Recorded At'), default=now, blank=True)
client_ip = models.CharField(_('Client IP'), max_length=15, null=True, blank=True)
session_cookie_id = models.CharField(_('Session Cookie ID'), max_length=120, null=True, blank=True)
user_cookie_id = models.CharField(_('User Cookie ID'), max_length=120, null=True, blank=True)
user_id = models.CharField(_('User ID'), max_length=100, null=True, blank=True)
request_url = models.TextField(_('Request URL'), default='')
identifier = models.CharField(_('Identifier'), max_length=120, null=True, blank=True)
filename = models.TextField(_('Filename'), null=True)
size = models.PositiveBigIntegerField(_('Size'), null=True)
user_agent = models.TextField(_('User Agent'), default='')
# Alpha-2 ISO 3166 Codes: [Reference: Country Codes Alpha-2 & Alpha-3](https://www.iban.com/country-codes)
country = models.CharField(_('Country'), max_length=10, default='gb')
hit_type = models.CharField(_('Hit Type'), max_length=60, null=True, blank=True)
is_robot = models.BooleanField(_('Is Robot'), default=False)
is_machine = models.BooleanField(_('Is Machine'), default=False)发布于 2020-10-08 08:34:33
我认为您只能在python而不是QuerySet中这样做,因为Queryset是一个数据库"SELECT“表示,据我所知,您不能在查询集中包含字典”country-count“,而不能在自定义模型串行化方法或python代码中构建结果:
序列化程序示例
class LogItemSerializer(serializers.ModelSerializer):
country_counts = serializers.SerializerMethodField()
class Meta:
model = LogItem
def get_country_counts(self, obj):
# create the dic you want
result = {
"au": 6,
"jp": 1,
"us": 13
}
return resulthttps://stackoverflow.com/questions/64210244
复制相似问题