从列表中删除其相关相关模型相同的对象

时间:2013-10-17 15:05:04

标签: python django

我认为从问题中理解问题非常困难,所以我会提供答案。

我的模型之间有以下关系:Answer BelongsTo Question属于Page。我有一份答案清单:[<Answer: 1>, <Answer: 2>, ...]

现在,我想删除属于相同页面的不同问题的所有答案。

例如,如果我的答案列表包含以下内容(为了清晰起见而添加了详细信息):[<Answer: Q1P1>, <Answer: Q1P1>, <Answer: Q1P2>, <Answer: Q2P2>]那么只应从列表中删除最后的两个答案,因为它们都属于对属于同一页面的不同问题。前两个答案仍然存在,因为虽然他们的问题属于同一页面,但问题并没有区别

我的模型大致如下:

class Page(models.Model):
    pass

class Question(models.Model):
    page = models.ForeignKey(Page)

class Answer(models.Model):
    question = models.ForeignKey(Question)

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

更新2:

假设我们有一个answers列表。

# 1. Let's find out the pages:
pages = set([])
for a in answers:
 pages.add(a.question.page)
pages = list(pages)

# 2. Now for each page, 
for p in pages:
  # 2.a. find out the answers that belong to this page
  same_page_answers = [a for a in answers if a.question.page = p]
  # 2.b. find out the questions of these answers
  same_page_questions = set([])
  for a in same_page_answers:
    same_page_questions.add(a.question)
  same_page_questions = list(same_page_questions) 

  # 3. now we will check to see if each question appears at least twice
  for q in same_page_questions:
    same_page_question_answers = [a for a in same_page_answers if a.question=q]
    if len(same_page_question_answer) < 2:
      # Ok so the same_page_question_answers need to be removed from our initial answers
      answers = [a for a in answers if a not in same_page_question_answer]
      # actually if we are here same_page_question_answer will be an array with 1 element but in any case

使用您的示例


answers = [A1: Q1P1, A2: Q1P1, A3: Q1P2, A4: Q2P2]

pages = [P1, P2]

inside for loop for P1:
 same_page_answers = [A1, A2]
 same_page_questions = [Q1, Q1]
 inside for loop for Q1:
  len == 2 - we won't remove anything


inside for loop for P2:
 same_page_answers = [A3, A4]
 same_page_questions = [Q1, Q2]
 inside for loop for Q1:
  same_page_question_answers = [A3]
  len = 1 - we will remove [A3] from answers
 inside for loop for Q2:
  same_page_question_answers = [A4]
  len = 1 - we will remove [A4] from answers

answers = [A1,A2]

希望它现在正在运作:)