coleifer/peewee — pull request #102 by tmoertel (2012-07-31 23:07:03+00:00)
Title: Add support for querying models by primary-key value

This (tiny!) patch allows you to query for a model instance by simply
providing its primary-key value as a query argument. You can use this
new convention anywhere Q objects are allowed, but the most-common
expected use case is this:

blog = Blog.get(1) # get blog w/ primary key of 1

Rationale.

Why this patch? In short, because it simplifies one common use-case
and eliminates the need to break encapsulation for another.

Currently, to fetch a model instance when you know its primary-key
value, you must also know its primary-key name:

blog = Blog.get(id=1) # relies on knowledge that Blog's pkey is "id"

Since the model already has this knowledge, why not just let the model
take care of it?

blog = Blog.get(1)

Moreover, when writing generic code that takes a model as a parameter,
you must pry into peewee's internals to learn what the model's primary
key is called. For example:

def get_required_web_model_instance(model, id):
try:
return model.get(**{model._meta.pk_name: id}) # naughty!
except model.DoesNotExist:
raise flask.abort(404)

If we let the model take care of the details, however, we need not
breach peewee's encapsulation barriers to write model-generic code:

def get_required_web_model_instance(model, id):
try:
return model.get(id) # nice!
except model.DoesNotExist:
raise flask.abort(404)