Django查询过滤器语法问题

时间:2019-04-09 02:20:14

标签: python django

我正在将Django 1.10.5与python 3.6结合使用。

我有以下模型类:

([[:blank:]]+)

在很多帮助下,我有一个查询,它将返回活动类型1的所有详细信息:

class PublishedDetails(FillableModelWithLanguageVersion):
  user = models.ForeignKey(settings.AUTH_USER_MODEL)
  ....

class PublishedRecordedActivity(models.Model):
    published_details = models.ForeignKey(PublishedDetails, null=False, blank=False, on_delete=models.CASCADE)
    timestamp_added = models.DateTimeField(auto_now_add=True)
    activity_type = models.IntegerField(null=False, blank=False, default=1)

但是,我现在只想返回查询以获取特定的已发布详细信息。例如aggregated_type_1 = PublishedRecordedActivity.objects.filter( activity_type=1).annotate(month=TruncMonth('timestamp_added')).values( 'month').annotate(sum_by_month=Count('month')).order_by('-timestamp_added') ,其中73是模型/表published_details=73中的id值。

所以我扩展了查询,但收到错误:PublisheDetails

我已将模型导入视图。

这是令人讨厌的查询:

'publisheddetails__id' is not defined

我尝试了回溯,并且引用了django文档,但是解决方案使我逃脱了。

3 个答案:

答案 0 :(得分:1)

为什么会出错?

错误 'publisheddetails__id' is not defined 是一个基本的Python错误,表明您没有在范围内定义变量 publisheddetails__id 示例

In [1]: foo=1                                                                                                                                                                                                      

In [2]: foo_bar                                                                                                                                                                                                    
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-7d351c29d631> in <module>
----> 1 foo_bar

NameError: name 'foo_bar' is not defined

在上面的示例中,我们定义了变量 foo ,但是我们尝试访问变量 foo_bar 。因此,Python解释器将引发异常


解决方案?

在使用变量之前定义变量

publisheddetails__id = 73
aggregated_type_1 = PublishedRecordedActivity.objects.filter(
    activity_type=1, published_details=publisheddetails__id).annotate(month=TruncMonth('timestamp_added')).values(
    'month').annotate(sum_by_month=Count('month')).order_by('-timestamp_added')

答案 1 :(得分:0)

您需要为发布的详细信息传递id。在published_details=publisheddetails__id中,查询实际上是在寻找id,但它得到publisheddetails__id的定义。 相反,您可以尝试定义一个变量并将其传递。

pub_details_id=73
aggregated_type_1 = PublishedRecordedActivity.objects.filter(
activity_type=1, published_details=pub_details_id).annotate(month=TruncMonth('timestamp_added')).values(
'month').annotate(sum_by_month=Count('month')).order_by('-timestamp_added')

答案 2 :(得分:0)

尝试一下:

published_details=publisheddetails

或:

published_details__id=publisheddetails.id