tags:

views:

33

answers:

2

Hi, Is it possible to have a field in a Django model which does not get stored in the database.
For example:

class Book(models.Model):
    title = models.CharField(max_length=75)
    description models.CharField(max_length=255, blank=True)
    pages = models.IntegerField()
    none_db_field = ????

I could then do

book = Book.objects.get(pk=1)
book.none_db_field = 'some text...'
print book.none_db_field

Thanks

+1  A: 

Creating a property on the model will do this, but you won't be able to query on it.

Ignacio Vazquez-Abrams
Thanks for your answer. I've just tried this and it worked though. I added none_db_field = None to my model. I then tried:book.none_db_field = "testing" print book.none_db_fieldand it worked.Is this ok to do in Django?
John
Adding it to the model like that makes it a class attribute, which may or may not be what you want. Normally instance attributes are created in the `__init__()` method.
Ignacio Vazquez-Abrams
A: 

As long as you do not want the property to persist, I don't see why you can't create a property like you described. I actually do the same thing on certain models to determine which are editable.

class Email(EntryObj):
    ts = models.DateTimeField(auto_now_add=True)
    body = models.TextField(blank=True)
    user = models.ForeignKey(User, blank=True, null=True)
    editable = False
    ...


class Note(EntryObj):
    ts = models.DateTimeField(auto_now_add=True)
    note = models.TextField(blank=True)
    user = models.ForeignKey(User, blank=True, null=True)
    editable = True
Jack M.