我有这个
b_articles = tc.tc_buch_articles.all()
j_articles = tc.tc_journal_articles.all()
joined = itertools.chain(b_articles, j_articles)
sorter = lambda x: x.article_in_collection__year if hasattr(x, 'article_in_collection__year') else x.article_in_journal__year
articles = sorted(joined, key = sorter, reverse=True)
以下是我的模特
我收到错误:
'EntryArticleInCollection' object has no attribute 'article_in_journal__year'
我想达到这样的结果:
a = 1, 3, 8, 10
b = 2, 3, 5, 12
res = 1, 2, 3, 3, 5, 8, 10, 12
模特:
class TopicCenter(models.Model):
user = models.ForeignKey(Person,related_name="user_tcs")
title = models.TextField()
subtitle = models.TextField()
class ArticleInCollection(models.Model):
user = models.ForeignKey(Person,related_name="user_buchaufsatz")
title = models.TextField()
book = models.ForeignKey(Book,related_name="book_aufsatze")
added = models.DateTimeField(auto_now_add=True, blank=True)
year = models.IntegerField(default=0000)
class ArticleInJournal(models.Model):
user = models.ForeignKey(Person,related_name="user_journalaufsatz")
title = models.TextField()
journal = models.ForeignKey(Journal,related_name="journal_aufsatze")
added = models.DateTimeField(auto_now_add=True, blank=True)
year = models.IntegerField(default=0000)
class EntryArticleInCollection(models.Model):
added = models.DateTimeField(auto_now_add=True, blank=True)
lastmodified = models.DateTimeField(auto_now=True, blank=True)
topiccenter = models.ForeignKey(TopicCenter,related_name="tc_buch_articles")
article_in_collection = models.ForeignKey(ArticleInCollection,related_name="bucharticle_entries")
class EntryArticleInJournal(models.Model):
added = models.DateTimeField(auto_now_add=True, blank=True)
lastmodified = models.DateTimeField(auto_now=True, blank=True)
topiccenter = models.ForeignKey(TopicCenter,related_name="tc_journal_articles")
article_in_journal = models.ForeignKey(ArticleInJournal,related_name="journal_article_entries")
答案 0 :(得分:2)
这种getattr()
方法怎么样:
sorter = lambda x: getattr(x, 'article_in_collection', x.article_in_journal).year
或:
def sorter(x):
try:
return x.article_in_collection.year
except AttributeError:
return x.article_in_journal.year
您的解决方案的问题在于您首先需要获取ForeignKey
字段,然后通过dot notation
获取相关模型上的字段。在这种情况下,双下划线方法不起作用。