Skip to main content
 首页 » 编程设计

python之Django类继承创建table表

2025年05月04日24birdshome

我开始学习 Django 并为 MySQL 数据库设置模型。我希望我的一个类继承另一个类,以便属性继承到表中。

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 

然而,当我运行 python manage.py syncdb 时,表“videos”只有一个主 ID 列和一个提供者列。是否有必要重新声明 Images 中的所有列并将 Videos 设置为完全独立的类,或者我是否可以将所有这些列继承到 Videos 类中?

请您参考如下方法:

2 件事:

1)可以考虑使用抽象基类

2) 在你的选择中对常量使用全大写

要回答您的问题,您不需要重新声明所有列。

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