File: managers_models.rst

package info (click to toggle)
python-django-postgres-extra 2.0.9-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,096 kB
  • sloc: python: 9,057; makefile: 17; sh: 7; sql: 1
file content (68 lines) | stat: -rw-r--r-- 2,034 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
.. _managers_models:

Managers & Models
=================

:class:`~psqlextra.manager.PostgresManager` exposes a lot of functionality. Your model must use this manager in order to use most of this package's functionality.

There are four ways to do this:

* Inherit your model from :class:`psqlextra.models.PostgresModel`:

   .. code-block:: python

      from psqlextra.models import PostgresModel

      class MyModel(PostgresModel):
          myfield = models.CharField(max_length=255)


* Override default manager with :class:`psqlextra.manager.PostgresManager`:

   .. code-block:: python

      from django.db import models
      from psqlextra.manager import PostgresManager

      class MyModel(models.Model):
          # override default django manager
          objects = PostgresManager()

          myfield = models.CharField(max_length=255)


* Provide :class:`psqlextra.manager.PostgresManager` as a custom manager:

   .. code-block:: python

      from django.db import models
      from psqlextra.manager import PostgresManager

      class MyModel(models.Model):
          # custom mananger name
          beer = PostgresManager()

          myfield = models.CharField(max_length=255)

      # use like this:
      MyModel.beer.upsert(..)

      # not like this:
      MyModel.objects.upsert(..) # error!


* Use the :meth:`psqlextra.util.postgres_manager` on the fly:

    This allows the manager to be used **anywhere** on **any** model, but only within the context. This is especially useful if you want to do upserts into Django's :class:`~django:django.db.models.ManyToManyField` generated :attr:`~django:django.db.models.ManyToManyField.through` table:

   .. code-block:: python

      from django.db import models
      from psqlextra.util import postgres_manager

      class MyModel(models.Model):
          myself = models.ManyToManyField('self')

      # within the context, you can access psqlextra features
      with postgres_manager(MyModel.myself.through) as manager:
          manager.upsert(...)