使用django

时间:2017-07-18 05:42:22

标签: django django-orm

我正在尝试获取一个查询集,其中一个任务有两个已在10秒内创建的发行。

模型如下:

Class Task(models.Model):
    # stuff

Class Issuance(models.Model):
    task = models.ForeignKey(Task, blank=True, null=True, on_delete=models.SET_NULL)
    created = models.DateTimeField(default=timezone.now)

到目前为止我得到了什么:

qs = (
    Task.objects
    .annotate(count=Count('issuance'))
    .filter(count__gt=1, count__lte=2)
    .annotate(time_difference=F('issuance__created'))  # Need to fix this
    .annotate(
        dupe=Case(
            When(
                time_difference__lt=10,  # Less than 10 seconds
                then=Value(1),
            ),
            default=Value(0),
            output=BooleanField(),
        )
    )
)

我认为我非常接近但我需要一些方法来计算任何一个任务的两个发行的创建日期之间的时间差。另外,需要进行时间差小于10秒的比较;不确定我的工作是否有效。

有人可以帮忙吗?

编辑:添加了查询输出

TypeError                                 Traceback (most recent call last)
<ipython-input-47-e0e60776551e> in <module>()
     11             ),
     12             default=Value(0),
---> 13             output=BooleanField(),
     14         )
     15     )

/usr/local/lib/python3.6/site-packages/django/db/models/query.py in annotate(self, *args, **kwargs)
    912                 raise ValueError("The annotation '%s' conflicts with a field on "
    913                                  "the model." % alias)
--> 914             clone.query.add_annotation(annotation, alias, is_summary=False)
    915 
    916         for alias, annotation in clone.query.annotations.items():

/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py in add_annotation(self, annotation, alias, is_summary)
    969         """
    970         annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None,
--> 971                                                    summarize=is_summary)
    972         self.append_annotation_mask([alias])
    973         self.annotations[alias] = annotation

/usr/local/lib/python3.6/site-packages/django/db/models/expressions.py in resolve_expression(self, query, allow_joins, reuse, summarize, for_save)
    827         c.is_summary = summarize
    828         for pos, case in enumerate(c.cases):
--> 829             c.cases[pos] = case.resolve_expression(query, allow_joins, reuse, summarize, for_save)
    830         c.default = c.default.resolve_expression(query, allow_joins, reuse, summarize, for_save)
    831         return c

/usr/local/lib/python3.6/site-packages/django/db/models/expressions.py in resolve_expression(self, query, allow_joins, reuse, summarize, for_save)
    760         c.is_summary = summarize
    761         if hasattr(c.condition, 'resolve_expression'):
--> 762             c.condition = c.condition.resolve_expression(query, allow_joins, reuse, summarize, False)
    763         c.result = c.result.resolve_expression(query, allow_joins, reuse, summarize, for_save)
    764         return c

/usr/local/lib/python3.6/site-packages/django/db/models/query_utils.py in resolve_expression(self, query, allow_joins, reuse, summarize, for_save)
     79         # We must promote any new joins to left outer joins so that when Q is
     80         # used as an expression, rows aren't filtered due to joins.
---> 81         clause, joins = query._add_q(self, reuse, allow_joins=allow_joins, split_subq=False)
     82         query.promote_joins(joins)
     83         return clause

/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py in _add_q(self, q_object, used_aliases, branch_negated, current_negated, allow_joins, split_subq)
   1251                     child, can_reuse=used_aliases, branch_negated=branch_negated,
   1252                     current_negated=current_negated, connector=connector,
-> 1253                     allow_joins=allow_joins, split_subq=split_subq,
   1254                 )
   1255                 joinpromoter.add_votes(needed_inner)

/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py in build_filter(self, filter_expr, branch_negated, current_negated, can_reuse, connector, allow_joins, split_subq)
   1141         clause = self.where_class()
   1142         if reffed_expression:
-> 1143             condition = self.build_lookup(lookups, reffed_expression, value)
   1144             clause.add(condition, AND)
   1145             return clause, []

/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py in build_lookup(self, lookups, lhs, rhs)
   1081                     lhs = self.try_transform(lhs, name, lookups)
   1082                     final_lookup = lhs.get_lookup('exact')
-> 1083                 return final_lookup(lhs, rhs)
   1084             lhs = self.try_transform(lhs, name, lookups)
   1085             lookups = lookups[1:]

/usr/local/lib/python3.6/site-packages/django/db/models/lookups.py in __init__(self, lhs, rhs)
     17     def __init__(self, lhs, rhs):
     18         self.lhs, self.rhs = lhs, rhs
---> 19         self.rhs = self.get_prep_lookup()
     20         if hasattr(self.lhs, 'get_bilateral_transforms'):
     21             bilateral_transforms = self.lhs.get_bilateral_transforms()

/usr/local/lib/python3.6/site-packages/django/db/models/lookups.py in get_prep_lookup(self)
     57             return self.rhs._prepare(self.lhs.output_field)
     58         if self.prepare_rhs and hasattr(self.lhs.output_field, 'get_prep_value'):
---> 59             return self.lhs.output_field.get_prep_value(self.rhs)
     60         return self.rhs
     61 

/usr/local/lib/python3.6/site-packages/django/db/models/fields/__init__.py in get_prep_value(self, value)
   1415 
   1416     def get_prep_value(self, value):
-> 1417         value = super(DateTimeField, self).get_prep_value(value)
   1418         value = self.to_python(value)
   1419         if value is not None and settings.USE_TZ and timezone.is_naive(value):

/usr/local/lib/python3.6/site-packages/django/db/models/fields/__init__.py in get_prep_value(self, value)
   1273     def get_prep_value(self, value):
   1274         value = super(DateField, self).get_prep_value(value)
-> 1275         return self.to_python(value)
   1276 
   1277     def get_db_prep_value(self, value, connection, prepared=False):

/usr/local/lib/python3.6/site-packages/django/db/models/fields/__init__.py in to_python(self, value)
   1376 
   1377         try:
-> 1378             parsed = parse_datetime(value)
   1379             if parsed is not None:
   1380                 return parsed

/usr/local/lib/python3.6/site-packages/django/utils/dateparse.py in parse_datetime(value)
     91     Returns None if the input isn't well formatted.
     92     """
---> 93     match = datetime_re.match(value)
     94     if match:
     95         kw = match.groupdict()

TypeError: expected string or bytes-like object

0 个答案:

没有答案