Fake model field

632 views
Skip to first unread message

Doug B

unread,
Nov 28, 2007, 3:33:46 PM11/28/07
to Django users
Is there a way to make custom model field that works normally except
for database interaction where it is ignored. In looking at the
source it doesn't seem possible but I thought it couldn't hurt to ask.

I have a serialized model field, based on a text field. I usually use
it to store random bits of data in a python dict that may vary from
model to model, or for playing around where I don't want to deal with
changing the database schema.

What I've done is also create a descriptor class that allows me to
access keys in the serialized field as if they were model
properties.

class SomeModel(models.Model):
extra = cJSONField()
prefs=DynField('_prefs','extra')
logos=DynField('_logos','extra')
allowed=DynField('_allowed','extra')

here extra is just the serialized field, and prefs,logs, and allowed
are fake fields that get/set data from the serialized field according
to their assigned keys. So I've basically got something like

extra = {'_prefs': value1, '_logos',value2, '_allowed': value3}

that is serialized and stored in the database.

Everything works fine, except I'd really like to have those fields
available in the Admin app, which they would be if I could disguise
them a bit and stick em in with the real model fields so the Admin
could recognize them.

In case my example wasn't clear, here is the code.
http://dpaste.com/26157/

Malcolm Tredinnick

unread,
Nov 28, 2007, 3:37:47 PM11/28/07
to django...@googlegroups.com

On Wed, 2007-11-28 at 12:33 -0800, Doug B wrote:
> Is there a way to make custom model field that works normally except
> for database interaction where it is ignored. In looking at the
> source it doesn't seem possible but I thought it couldn't hurt to ask.

No. You're going to really have to do this yourself. Pretty much by
definition, a django.db.models.field.* class is something that is
persisted to the database. Everything else would be just a normal Python
property.

You could take inspiration from GenericRelation fields, although (a)
there's some risk that your head will explode when reading the code
because it's a little scary and (b) they don't work in admin yet, so
your primary use-case doesn't have an example to copy. My understanding
is that the latter case is because is just isn't done yet (but is in
progress), rather than because it's fundamentally hard.

Malcolm


Reply all
Reply to author
Forward
0 new messages