如何避免django项目中出现重复模型?

发布于 2024-09-27 06:50:56 字数 105 浏览 2 评论 0原文

我正在学习 Django,所以我有很多问题,其中一个是如何重用模型?我的意思是模型位于应用程序文件夹中,但某些模型在两个不同的应用程序之间完全相同。 那么每次编写新应用程序时我都应该重写模型吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

九局 2024-10-04 06:50:56

是的,当您的应用程序具有相同名称时,这是错误的
您还可以使用 抽象型号


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)

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)

浊酒尽余欢 2024-10-04 06:50:56

如果您的模型在不同的应用程序中完全相同,那么您就做错了。不要忘记,应用程序基本上只是一组模型,您只需导入一个应用程序的模型即可在另一个应用程序中使用它们。

您能举一个具有完全相同模型的两个应用程序的示例吗?

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?

假扮的天使 2024-10-04 06:50:56

如何重用模型

重用模型的最佳方法是继承父模型类。你必须这样做。继承自 models.Model。

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

另请确保在适当的 models.py 文件中导入您的应用模型。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文