Code


Version 2 (modified by rjwittams, 9 years ago) (diff)

--

In this proposal, fields would become descriptors.

This means

  • They would be left as members by the metaclass.
  • The real 'data' would end up either in name-mangled instance members, or in a private dictionary.
  • When accessed via the class, they would return themselves. eg Reporter.name would be a field class you can inspect. This would make introspection as in the admin easier.
  • When accessed via the instance, they would return a representation of the value they hold. This could be
    • the simple data instance from the private dict that was fetched from the db.
    • a lazily computed value, eg a BLOB field which would be fetched from the db on first access, not at initial load time, or a ForeignKey relationship that hasn't been loaded yet.
  • ForeignKeys and other related fields would place another descriptor on the related class. When accessed via the instance, this would return a lazy collection object. It will act like a set (an ordered one if there is an ordering involved).

This would also support other methods in favour of the get_related_list things.

So:

 reporter.get_article_list()
 reporter.get_article_list(headline__startswith='This', order_by=['headline'])
 reporter.add_article(headline="John's second story", pub_date=datetime(2005, 7, 29))

would change to:

 reporter.article_set
 reporter.article_set.filter(headline__startswith='This').order_by('headline')
 reporter.article_set.add(headline="John's second story", pub_date=datetime(2005, 7, 29))

Methods which change the meaning of the lazy collection are as follows: .filter : adds query parameters using djangos normal db query syntax. .order_by: adds/changes ordering parameters.

Other methods of a similar style are also possible.

.add would add a new instance of the related class to the collection.

This would register a callback so that it would be written to the db when .save() is called on the parent object.