簡體   English   中英

過濾由appengine使用django創建的ReferenceModel的下拉列表

[英]Filtering the drop down list of ReferenceModels created by appengine using django

我的App Engine項目中有一些課程

class First(db.Model):
  count = db.IntegerProperty()

class Second(db.Model):
  first = db.ReferenceProperty(First)

class SecondForm(djangoforms.ModelForm)
  class Meta:
    model = Second

SecondForm模型在渲染時會在模板中生成一個非常漂亮的下拉菜單,但是當前它會首先顯示所有類型的Models。 我在徘徊,如果有人有一個優雅的策略允許將條件放在返回的對象上(例如,first.count> 10)以減少將在下拉列表中呈現的對象的數量。

謝謝,

理查德

將以下init方法添加到SecondForm類中:

def __init__(self, *args, **kwargs):
    super(SecondForm, self).__init__(*args, **kwargs)
    self.fields['first'].query = db.Query(First).fetch(10)

在查詢中添加過濾器等,以控制下拉列表的內容!

我沒有使用App Engine的經驗,但是此食譜可能會對您有所幫助:

http://appengine-cookbook.appspot.com/recipe/django-modelchoicefield-filter-input-select-by-foreign-key/

他們正在傳遞一個過濾器值,但是我確信您可以通過閱讀該文章獲得所需的信息。

對於那些對將下拉菜單的范圍縮小到僅祖先對象的完整解決方案感興趣的人,我將其粘貼在下面。 然后,如果您使用(parent = ...)設置模型並使用類似於下面的形式,則下拉菜單中只會顯示祖先。 請享用。

class WombatForm(djangoforms.ModelForm):
  def __init__(self, *args, **kwargs):
    super(WombatForm, self).__init__(*args, **kwargs)
    for field_name in self.fields:
      field_model = self.fields[field_name] 
      if isinstance(field_model,djangoforms.ModelChoiceField):
        root = WombatForm.get_root_node(self.instance)
        self.fields[field_name].query.ancestor(root)

@staticmethod
def  get_root_node(entity):
  '''
    returns the final parent ancestor of the given entity
  '''
  parent_ent = entity.parent()
  if parent_ent == None:
    return entity
  return WombatForm.get_root_node(parent_ent)

class SecondForm(WombatForm)
  class Meta:
    model = Second

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM