python排序和链-django查询集

python排序和链-django查询集,python,django,Python,Django,我有这个 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

我有这个

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")

这种方法怎么样

sorter = lambda x: getattr(x, 'article_in_collection', x.article_in_journal).year
或:


您的解决方案存在的问题是,首先需要获取
ForeignKey
字段,然后通过
dot notation
获取相关模型上的字段。双下划线方法在这种情况下不起作用。

你能显示你的模型定义吗?@alecxe我用我的模型更新了这个问题,我的意思是:
“EntryArticleInCollection”对象没有属性“article\u in\u journal”
啊,我明白了。所以,一旦我进入sorted()函数,fkeys中就没有更深入的查找了?但它必须以某种方式解决:(@doniyor好的,让我们挖掘一下。这个
分拣机
sorter=lambda x:x.added
?随着
added
,它正在工作-给出按added排序的结果field@doniyor谢谢,那么,如果您将
b_文章
单独排序:
sorted(b_articles,key=lambda x:x.article_in_collection.year)
def sorter(x): 
    try: 
        return x.article_in_collection.year 
    except AttributeError: 
        return x.article_in_journal.year