我有这样的书模型:
class Book(models.Model):
authors = models.ManyToManyField(Author, ...)
...
Run Code Online (Sandbox Code Playgroud)
简而言之:
我想检索作者严格等于给定作者集的书籍.我不确定是否有单个查询可以执行此操作,但任何建议都会有所帮助.
长期:
这是我尝试过的(无法运行获取AttributeError)
# A sample set of authors
target_authors = set((author_1, author_2))
# To reduce the search space,
# first retrieve those books with just 2 authors.
candidate_books = Book.objects.annotate(c=Count('authors')).filter(c=len(target_authors))
final_books = QuerySet()
for author in target_authors:
temp_books = candidate_books.filter(authors__in=[author])
final_books = final_books and temp_books
Run Code Online (Sandbox Code Playgroud)
......这就是我得到的:
AttributeError: 'NoneType' object has no attribute '_meta'
Run Code Online (Sandbox Code Playgroud)
一般来说,我应该如何查询模型,其约束条件是其ManyToMany字段包含一组给定的对象,就像我的情况一样?
ps:我发现了一些相关的SO问题,但无法得到明确的答案.任何好的指针也会有所帮助.谢谢.
假设我有一个Python类:
class Foo(object):
a = 1
b = 2
Run Code Online (Sandbox Code Playgroud)
当我访问'a'但不是'b'时,我想做一些额外的事情.所以,例如,让我们假设我想要做的额外事情是增加属性的值:
> f = Foo()
> f.a # Should output 2
> f.a # Should output 3
> f.a # Should output 4
> f.b # Should output 2, since I want the extra behavior just on 'a'
Run Code Online (Sandbox Code Playgroud)
感觉有一种方法可以通过__getattr__或__getattribute__,但我无法理解这一点.
额外的东西可以是任何东西,不一定与属性相关(如打印'Hello world').
谢谢.