开发者

Model relationship to html template

I've been struggling for this issue for a few hours - I know there's probably a simple solution that I'm overlooking.

I have a one to many relationship with my models.

I have need to return all rows of one object with the rows for the related object.

In a sense I have this:

 object 
 object
   object_relationship.property
   object_relationship.property
object
   object_relationship.property
object

Now - I can run through al开发者_Go百科l of these fine, but I run into an issue when I want to send these back to the html template.

I can send the object back - but how do I send the object_relationship back in the order that I have it above?

Does this make sense?


You might not need to worry too much about this, acutally... look at these models:

class Venue(base.NamedEntity, HasPerformances, HasUrl, HasLocation):
    city = db.ReferenceProperty(City, collection_name='venues')
    url = db.StringProperty(required=True, validator=validators.validate_url)
    location = db.GeoPtProperty()

class Performance(base.Entity):
    show = db.ReferenceProperty(Show, collection_name='performances', required=True)
    utc_date_time = db.DateTimeProperty(required=True)
    venue = db.ReferenceProperty(Venue, collection_name='performances', required=True)

In a case like this, nothing stops you from using venue.performances from either code or templates and treating it as a list. The API will automatically fire queries as needed to fetch the actual objects. The same thing goes for performance.venue.

The only problem here is performance - you've got a variant of the n+1 problem to deal with. There are workarounds, though, like this article by Nick Johnson. I'd suggest reading the API code too... it makes for interesting reading how the property get is captured and dereferenced.


My first suggestion is to denormalize the data if you are going to do many reports like that. For example, maybe you could include object.name on the object_relationship entity.

That said, you could send a list of dicts to your template, so maybe something like:

data = []
for entity in your_query:
   children = [{'name': child.name} for child in entity.object_relation]
   data.append({'name': object.name,
                'children': children,
                 ...
               })

Then pass the data list to your template, and process it.

Please note, this will perform very badly. It will execute another query for every one of the items in your first query. Use Appstats to profile your app.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜