Reputation: 15207
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
Upvotes: 1
Views: 441
Reputation: 15207
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
Upvotes: 0
Reputation: 9457
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!!
Upvotes: 2
Reputation: 39287
I don't have experience using App Engine, but this recipe might help you out:
They are passing in a filter value, but I'm sure you can get what you need from reading through that post.
Upvotes: 1