简体   繁体   中英

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

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 conditions 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM