3

I'm beginning to learn Django and setting up my models for a MySQL database. I'd like one of my classes to inherit another class so that the properties carry on to the table.

from django.db import models

class Images(models.Model):
    category    = models.ForeignKey(Categories)
    title       = models.CharField(max_length=250)
    caption     = models.CharField(max_length=250)
    date        = models.DateTimeField('date published')
    url         = models.CharField(max_length=250)

    class Meta:
        verbose_name_plural = 'images'

    def __unicode__(self):
        return self.category

class Videos(Images):

    provider_list   = (('YU','YouTube'),('VI','Vimeo'))
    provider        = models.CharField(max_length=2, choices=provider_list)

    class Meta:
        verbose_name_plural = 'videos'

    def __unicode__(self):
        return self.category

When I run python manage.py syncdb however, the table "videos" only has a primary ID column and a provider column. Is it necessary to redeclare all of the columns from Images and set up Videos as a completely independence class or is there anyway I can inherit all of these columns into the Videos class?

1 Answer 1

2

2 things:

1) You can consider using abstract base class

2) Use full caps for constants in your choices

To answer your questions you do not need to redeclare all the columns.

from django.db import models

class BaseMedia(models.Model):
    category    = models.ForeignKey(Categories)
    title       = models.CharField(max_length=250)
    caption     = models.CharField(max_length=250)
    date        = models.DateTimeField('date published')
    url         = models.CharField(max_length=250)

    class Meta:
        abstract = True

class Images(BaseMedia):

    class Meta:
        verbose_name_plural = 'images'

    def __unicode__(self):
        return self.category

class Videos(BaseMedia):

    PROVIDER_LIST_CHOICES   = (('YU','YouTube'),('VI','Vimeo'))
    provider        = models.CharField(max_length=2, choices=PROVIDER_LIST_CHOICES)

    class Meta:
        verbose_name_plural = 'videos'

    def __unicode__(self):
        return self.category
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.