开发者

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

开发者 https://www.devze.com 2023-03-01 08:50 出处:网络
I have some classes in my app engine project class First(db.Model): count = db.IntegerProperty() class Second(db.Model):

I have some classes in my app engine project

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

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

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

The SecondForm model generates a really nice drop down menu in the template when rendered but it currently displays all the Models of type first. I was wandering if anyone had an elegant strategy allow conditio开发者_运维技巧ns to be placed on the objects returned (such as to first.count > 10) to reduce the number of objects that will be rendered in the drop down list.

Thanks,

Richard


Add the following init method to the SecondForm class:

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

Add filters etc to the query to control the dropdown list contents!!


I don't have experience using App Engine, but this recipe might help you out:

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

They are passing in a filter value, but I'm sure you can get what you need from reading through that post.


For those interested in the complete solution of reducing the scope of the dropdown menu to only ancestor objects I've pasted it below. If you then set up a Model with (parent=...) and use a form similar to below, only the ancestors appear in the drop down. Enjoy.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消