开发者

How to avoid duplicate models in django project?

开发者 https://www.devze.com 2023-01-19 12:33 出处:网络
i\'m learning django so i\'ve many questions, and one is how i can reuse a model? i mean the models live in the application folder, but some models are exactly the same between two differents applicat

i'm learning django so i've many questions, and one is how i can reuse a model? i mean the models live in the application folder, but some models are exactly the same between two differents applications. So should i 开发者_开发问答rewrite the model every time that i write a new app?


Yes, this is wrong when you have the same names of yours apps You also can use abstract 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)


If your models are exactly the same in different applications, you're doing something wrong. Don't forget that an application is basically just a set of models, and you can use one application's models within another application just by importing them.

Can you give an example of two applications with exactly the same models?


How do I reuse a Model.

Best way to reuse model is to Inherit the parent Model class. This is how you must be doing it. Inheriting from models.Model.

from django.db import models
class trial(models.Model):
    # override the parent class methods here or define your own

Also make sure that you import your apps models in the appropriate models.py file.

0

精彩评论

暂无评论...
验证码 换一张
取 消