Friday, 29 December 2023

django model, managers, queryset functions and customizations

 every django model specified in core/models.py comes with default manager

https://docs.djangoproject.com/en/5.0/topics/db/managers/

https://stackoverflow.com/questions/26672077/django-model-vs-model-objects-create

By default, Django adds a Manager with the name objects to every Django model class. However, if you want to use objects as a field name, or if you want to use a name other than objects for the Manager, you can rename it on a per-model basis. To rename the Manager for a given class, define a class attribute of type models.Manager() on that model. For example:


Model.objects triggers default model manager, and Model.objects.create() triggers query set functions within the manager:

https://docs.djangoproject.com/en/5.0/ref/models/querysets/


// To customize manager and query set

https://stackoverflow.com/questions/5173343/override-django-get-or-create


class AccountQuerySet(models.query.QuerySet):

    def get_or_create(...):

        ...

You could then add a custom manager to your Account model which uses this custom QuerySet:


class AccountManager(models.Manager):

    def get_queryset(self):

        return AccountQuerySet(self.model)

Then use this manager in your model:


class Account(models.Model):

    ...

    objects = AccountManager()


# Account.objects will now refer to AccountManager class in this case, and Account.objects.get_or_create will refer to AccountQuerySet



// to import a model to your view.py

from core.models import myModelClass

myModelClass.objects.create()


or if you have nested folder structure:

https://stackoverflow.com/questions/31406662/django-unable-to-import-model-from-another-app

Bolton_GC [Folder]

- Bolton_GC [Folder]

  - News [Folder]

    - Migrations [Folder]

    - __init__.py

    - __init__.pyc

    - admin.py

    - admin.pyc

    - models.py

    - models.pyc

    - tests.py

    - views.py

......

- manage.py

from Bolton_GC.News.models import News_Article





No comments:

Post a Comment