loading django columns dynamically from another table

时间:2015-04-24 21:26:03

标签: django

Using django, I want to define several columns in my Xon model based on the unique values stored in MyTypes. This way, I do not need to manually define type1, type2, type3,... and I can use the admin page to dynamically add a new type column. Can someone explain how I can do that?

class Xon(models.Model):
    ge = models.CharField(max_length=200)
    mu = models.CharField(max_length=200)
    des = models.TextField()
    type1 = models.CharField(max_length=200)
    type2 = models.CharField(max_length=200)
    type3 = models.CharField(max_length=200)

class MyTypes(models.Model):
    name = models.CharField(max_length=20, primary_key=True)

1 个答案:

答案 0 :(得分:1)

Check out abstract base classes https://docs.djangoproject.com/en/1.8/topics/db/models/#abstract-base-classes

From the docs:

Abstract base classes

Abstract base classes are useful when you want to put some common information into a number of other models. You write your base class and put abstract=True in the Meta class. This model will then not be used to create any database table. Instead, when it is used as a base class for other models, its fields will be added to those of the child class. It is an error to have fields in the abstract base class with the same name as those in the child (and Django will raise an exception).

And an example, also from the docs:

from django.db import models

class CommonInfo(models.Model):
    name = models.CharField(max_length=100)
    age = models.PositiveIntegerField()

    class Meta:
        abstract = True

class Student(CommonInfo):
    home_group = models.CharField(max_length=5)