Django - 查询参数需要模型类型吗? RelatedObjectDoesNotExist:发帖有没有教科书
问题描述:
我已经安装了这个Django应用程序:http://django-auditlog.readthedocs.io/en/latest/_modules/auditlog/models.html#LogEntryDjango - 查询参数需要模型类型吗? RelatedObjectDoesNotExist:发帖有没有教科书
的日志条目设置两个不同的车型将在下面:
class Posting(models.Model):
textbook = models.ForeignKey(Textbook)
condition = models.CharField(max_length=200)
price = models.DecimalField(max_digits=5, decimal_places=2)
user = models.ForeignKey(User)
image = models.ImageField(upload_to='postingpics/%Y/%m/%d', default="/textchange/nophoto.png")
post_date = models.DateTimeField('date_posted')
comments = models.CharField(max_length=50, default="")
def __str__(self):
return str(self.textbook)
def was_posted_recently(self):
return self.post_date >= timezone.now() - datetime.timedelta(days=1)
was_posted_recently.admin_order_field = 'post_date'
was_posted_recently.boolean = True
was_posted_recently.short_description = 'Posted recently'
class Wishlist(models.Model):
textbook = models.ForeignKey(Textbook)
user = models.ForeignKey(User)
wish_date = models.DateTimeField('date_wish')
def __str__(self):
return str(self.textbook)
def was_wished_recently(self):
return self.wish_date >= timezone.now() - datetime.timedelta(days=1)
was_wished_recently.admin_order_field = 'date_wish'
was_wished_recently.boolean = True
was_wished_recently.short_description = 'Wished recently'
auditlog.register(Posting)
auditlog.register(Wishlist)
所以在数据库中的模型EntryLog是得到一个每次发生“发布”或“愿望清单”时发生的行都是删除,创建或更新。
我想完成下面的查询,因为我想统计一个过帐被删除的次数。另外我会为Wishlist做同样的查询。
LogEntry.objects.filter(action=2 , content_type=Posting).count()
content_type
是记录类型的外键。
当我运行此查询我得到的错误信息:
RelatedObjectDoesNotExist: Posting has no textbook.
这让我觉得,发帖是错误的价值摆在了content_type
。我是否正确思考这个问题? content_type
的值是否应该有所不同?我通常理解当你在外键字段如Posting__condition
或类似的东西上提到你正在查询的外键。
在此先感谢。
答
content_type
参数应该是ContentType
对象,而不是模型类。
而不是做这样做手工,你应该使用LogEntryManager
小号get_for_model
方法:
LogEntry.objects.get_for_model(Posting).filter(action=2).count()
+0
真棒,非常感谢 – Programmingjoe
添加完整的错误 – e4c5