Questions tagged «django-managers»

13
如何在Django中使用不同的设置进行单元测试?
是否有任何简单的机制可以覆盖Django单元测试的设置?我在一个模型上有一个经理,该经理返回特定数量的最新对象。它返回的对象数由NUM_LATEST设置定义。 如果有人更改设置,这可能会使我的测试失败。如何覆盖设置setUp()并随后恢复设置tearDown()?如果不可能,是否可以通过某种方式猴子修补方法或模拟设置? 编辑:这是我的经理代码: class LatestManager(models.Manager): """ Returns a specific number of the most recent public Articles as defined by the NEWS_LATEST_MAX setting. """ def get_query_set(self): num_latest = getattr(settings, 'NEWS_NUM_LATEST', 10) return super(LatestManager, self).get_query_set().filter(is_public=True)[:num_latest] 管理器用于settings.NEWS_LATEST_MAX切片查询集。该getattr()只是用来提供一个默认的应该设置不存在。

6
无法通过模型实例访问Manager
我正在尝试在另一个模型对象实例中获取此错误: Manager isn't accessible via topic instance 这是我的模型: class forum(models.Model): # Some attributs class topic(models.Model): # Some attributs class post(models.Model): # Some attributs def delete(self): forum = self.topic.forum super(post, self).delete() forum.topic_count = topic.objects.filter(forum = forum).count() 这是我的看法: def test(request, post_id): post = topic.objects.get(id = int(topic_id)) post.delete() 我得到: post.delete() forum.topic_count = topic.objects.filter(forum …

1
为什么要在Django models.Manager中定义create_foo()而不是覆盖create()?
阅读Django文档后,建议Foo通过create_foo在管理器中定义模型来为命名模型创建自定义创建方法: class BookManager(models.Manager): def create_book(self, title): book = self.create(title=title) # do something with the book return book class Book(models.Model): title = models.CharField(max_length=100) objects = BookManager() book = Book.objects.create_book("Pride and Prejudice") 我的问题是,为什么前一个方法更喜欢简单地重写基类的create方法: class BookManager(models.Manager): def create(self, title): book = self.model(title=title) # do something with the book book.save() return book class Book(models.Model): …
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.