Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transient use of Django Model instances

I have a use case where a particular class can either be transient or persistent. Transient instances are build from a JSON payload on a PUT call, and may either be persisted to the database or used during the server call and then either returned or discarded. What is best practice for this case? My options seem to be:

  • Write two classes, one of which is a models.Model subclass, and the other of which isn't, and make them implement the same API, or
  • Use the Model subclass, but be careful not to call save().

Is either of these preferable, according to conventional use of Django models?

like image 350
Scott Deerwester Avatar asked Oct 17 '25 15:10

Scott Deerwester


2 Answers

You'll need both:

abstract = True is useful if inheritants still should be concrete models, so that no table should be created just for the parent class. It allows you to opt out of multi-table inheritance, and instead have the shared attributes duplicated to inheritants tables instead (abstract base inheritance).

managed = False is useful if the inheriting class should never be persisted at all. Django migrations and fixtures won't generate any database table for this.

class TransientModel(models.Model):
    """Inherit from this class to use django constructors and serialization but no database management"""
    def save(*args, **kwargs):
        pass  # avoid exceptions if called

    class Meta:
        abstract = True  # no table for this class
        managed = False  # no database management

class Brutto(TransientModel):
    """This is not persisted. No table app_brutto"""
    #do more things here
    pass
like image 74
abstraktor Avatar answered Oct 20 '25 05:10

abstraktor


In order to remain as DRY as possible, you could have an abstract mock class deriving your model:

class A(models.Model):
    # fields'n'stuff

class TransientA(A):
    def save(*args, **kwargs):
        pass  # avoid exceptions if called

    class Meta:
        abstract = True  # no table created

Now, even if you call save on it anywhere (even in methods inherited from A), you'll be shooting blanks.

like image 20
user2390182 Avatar answered Oct 20 '25 05:10

user2390182