jackfrued / jackfrued/Python-100-Days
关于类、继承、函数、属性的综合性问题
Nobody has claimed this yet.
- Dominant language
- Jupyter Notebook
- Stars
- 187k
- Forks
- 55.8k
- PR merge metrics
- No merged PRs in 30d
Description
事情来源于 Django,但是我发现我的问题出在 Python 的基础知识上——学习了基础知识后发现,在一个实例面前我仍然手足无措,这真是一个悲伤的故事。
事儿是酱婶儿的:
Django 模型继承抽象基类时,子类如何继承抽象基类的字段并且重写字段的 db_column 值?
例如,系统中要定义大量的数据表,很多数据表都有 name 字段,因此将 name 字段放在抽象基类中,由模型继承抽象基类,以获得 name 字段,但是在模型中希望为 name 字段中加上个性化前缀以示区别,在以后的开发中避免混淆和出错,在子类中增加的这个前缀只作用在子类中,不影响抽象基类。
示例代码如下:
抽象基类的示例代码:
# 代码片段01
# 抽象基类
class CommonField(models.Model):
name = models.CharField(max_length=64, default="", db_column = 'name')
class Meta:
abstract = True
模型代码:
# 代码片段02
# 模型
class Category(CommonField)
prefix = 'ca' # 为分类表定义前缀为 ca
CommonField.rename.db_column = prefix + "_" + CommonField.rename.db_column
class Product
prefix = 'p' # 为产品表定义前缀为 p
CommonField.rename.db_column = prefix + "_" + CommonField.rename.db_column
期望是在 Category 表中创建 ca_name 字段,在 Product 表中创建 p_name 字段,然而在进行数据迁移生成迁移文件时, Django 就报错了:
AttributeError: 'DeferredAttribute' object has no attribute 'db_column'
执行环境为 Python 3.7; Django 3.X
下面完整写一下我的理解思路:
- 模型继承了
CommonField,则意味着当模型类完整继承了父类CommonField的全部代码,当模型类被实例化时,即意味着父类CommonField的代码被执行了一遍 - 在模型的实例化过程中,父类的代码什么时候被执行的?是先执行父类的代码,再执行子类的代码,还是先执行子类的代码,再执行父类的代码呢?
- 我想重命名父类的某个属性值,当然要在子类中传一个值,可是函数才能传值,调用类时怎么传值?
- 在父类中(示例中的抽象基类),
name才是属性,model.CharField这个方法应该是生成了一个对象,并且把这个对象赋值给了name,在model.CharField函数调用中,max_length、default、db_column应该都是关键字参数,这么理解没问题吧?我怎么才能把一个值传给某个关键字参数呢?
成年人看到的世界和孩子看到的世界是不同的,同样,Python 大师对代码的理解与新手也是不同的,我觉得这就是基础知识我没有完全理解,希望大师给个指导。
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
No repository file or test is named. Start by reviewing the issue's Django model examples and reproducing the migration-generation error with Python 3.7 and Django 3.x. Done means providing a clear explanation of abstract-model field inheritance, db_column overrides, and the relevant class-versus-instance behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- django, python
- Domain
- backend, databases, documentation
- Issue type
- Documentation
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100