[Fixed]-Create a new model which have all fields of currently existing model

21đź‘Ť

âś…

If your BookmarkPlayer needs the same data but in a different table, an abstract base model is the best way to go:

class BasePlayer(models.Model):
    name = models.CharField(max_length=100, null=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True)
    last_updated = models.DateTimeField(auto_now=True)
    hash = models.CharField(max_length=128, null=True, blank=True)
    bookmark_url = models.CharField(max_length=300, null=True, blank=True)

    class Meta:
        abstract = True

class Player(BasePlayer):
    """ player model """
    pass

class BookmarkPlayer(BasePlayer):
    """ bookmark player model """
    pass

This way, both Player and BookmarkPlayer inherit their fields from the BasePlayer model, but because BasePlayer is abstract, the models are completely decoupled.

Multi-table inheritance on the other hand would still save the fields in a single table, but add an extra table for the BookmarkPlayer with an implicit OneToOneField to the Player table.

👤knbk

0đź‘Ť

There are some good info about model inheritance here:
https://docs.djangoproject.com/en/1.7/topics/db/models/#model-inheritance

Option 2 will introduce duplication, which is always bad. If BookmarkPlayer will not have any new fields, only different methods, I would suggest you use the “proxy model” option described in the link, since you don’t need BookmarkPlayer to have it’s own table in the database.

If it needs it’s own table, “Multi-table inhertiance” is the way to go, which would be option 1 in your question

👤maillard

Leave a comment