Split models.py into several files

后端 未结 5 1427
轻奢々
轻奢々 2020-11-30 21:25

I\'m trying to split the models.py of my app into several files:

My first guess was do this:

myproject/
    settings.py
    manage.py
           


        
5条回答
  •  生来不讨喜
    2020-11-30 21:47

    I'd do the following:

    myproject/
        ...
        app1/
            views.py
            __init__.py
            models.py
            submodels/
                __init__.py
                model1.py
                model2.py
        app2/
            views.py
            __init__.py
            models.py
            submodels/
                __init__.py
                model3.py
                model4.py
    

    Then

    #myproject/app1/models.py:
        from submodels/model1.py import *
        from submodels/model2.py import *
    
    #myproject/app2/models.py:
        from submodels/model3.py import *
        from submodels/model4.py import *
    

    But, if you don't have a good reason, put model1 and model2 directly in app1/models.py and model3 and model4 in app2/models.py

    ---second part---

    This is app1/submodels/model1.py file:

    from django.db import models
    class Store(models.Model):
        class Meta:
            app_label = "store"
    

    Thus correct your model3.py file:

    from django.db import models
    from app1.models import Store
    
    class Product(models.Model):
        store = models.ForeignKey(Store)
        class Meta:
            app_label = "product"
    

    Edited, in case this comes up again for someone: Check out django-schedule for an example of a project that does just this. https://github.com/thauber/django-schedule/tree/master/schedule/models https://github.com/thauber/django-schedule/

提交回复
热议问题