在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/人工智能  Python/ Django 中如何批量創(chuàng)建models? 如何抽象出這個類?

Django 中如何批量創(chuàng)建models? 如何抽象出這個類?

一段代碼如下

from django.db import models
table_name = "新聞"
class Person(models.Model):
    class Meta:
        db_table = table_name
        app_label = table_name
    title = models.CharField("title", max_length=300)
    content = models.TextField("content", max_length=300)

現(xiàn)在的需求是,我如何把這個方法抽象出來?
意思就是說, 我直接給Person 這個類可以傳入?yún)?shù),然后在里面的class Meta中可以直接用

我最早想到是這樣

class Person(models.Model):
    def __init__(self,table_name):
         self.table_name = table_name
    class Meta:
        db_table = self.table_name
        app_label = self.table_name
    title = models.CharField("title", max_length=300)
    content = models.TextField("content", max_length=300)

但是失敗了,不能直接傳入?yún)?shù)? 這導(dǎo)致很不靈活,我如果有10個models要健 但是他們除了表名稱不一樣,其他都是一樣~
那這樣不是很不靈活

當(dāng)然也可以把這些數(shù)據(jù)全部放在一張表里面,但是感覺考慮到后期的數(shù)據(jù)量以及查詢效率的問題,還是想把表分開~

回答
編輯回答
瘋浪

Django models支持abstract=True屬性, 設(shè)置這個屬性后, 這個models不會在創(chuàng)建表, 專門用來繼承, 具體的可以看官方文檔 Models Abstract base classes部分.

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).

An example:

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)

The Student model will have three fields: name, age and home_group. The CommonInfo model cannot be used as a normal Django model, since it is an abstract base class. It does not generate a database table or have a manager, and cannot be instantiated or saved directly.

2017年5月23日 09:36
編輯回答
北城荒

可以試試用繼承

class Person(models.Model):
    class Meta:
        db_table = table_name
        app_label = table_name
    title = models.CharField("title", max_length=300)
    content = models.TextField("content", max_length=300)
    
    
class Person2(Person):
    class Meta:
        db_table = table_name
        app_label = table_name
    

或者使用元類去創(chuàng)建。

2017年1月7日 23:18