Non-database field in Django model

前端 未结 3 416
隐瞒了意图╮
隐瞒了意图╮ 2021-02-05 05:28

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.CharFie         


        
相关标签:
3条回答
  • 2021-02-05 06:03

    To make it an instance variable (so each instance gets its own copy), you'll want to do this

    class Book(models.Model):
        title = models.CharField(max_length=75)
        #etc
    
        def __init__(self, *args, **kwargs):
            super(Foo, self).__init__(*args, **kwargs)
            self.editable = False
    

    Each Book will now have an editable that wont be persisted to the database

    0 讨论(0)
  • 2021-02-05 06:12

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

    0 讨论(0)
  • 2021-02-05 06:20

    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
    
    0 讨论(0)
提交回复
热议问题