django sorcery documentation

109
Django Sorcery Documentation Release 0.11.3 Serkan Hosca Dec 06, 2021

Upload: others

Post on 19-Dec-2021

70 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Django Sorcery Documentation

Django Sorcery DocumentationRelease 0.11.3

Serkan Hosca

Dec 06, 2021

Page 2: Django Sorcery Documentation
Page 3: Django Sorcery Documentation

Contents

1 Installation 3

2 Quick Start 52.1 Changelog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152.2 API Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

3 Indices and tables 85

Python Module Index 87

Index 89

i

Page 4: Django Sorcery Documentation

ii

Page 5: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

GitHub: https://github.com/shosca/django-sorcery

SQLAlchemy is an excellent orm. And Django is a great framework, until you decide not to use Django ORM.This library provides utilities, helpers and configurations to ease the pain of using SQLAlchemy with Django. Itaims to provide a similar development experience to building a Django application with Django ORM, except withSQLAlchemy.

Contents 1

Page 6: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

2 Contents

Page 7: Django Sorcery Documentation

CHAPTER 1

Installation

pip install django-sorcery

3

Page 8: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

4 Chapter 1. Installation

Page 9: Django Sorcery Documentation

CHAPTER 2

Quick Start

Lets start by creating a site:

$ django-admin startproject mysite

And lets create an app:

$ cd mysite$ python manage.py startapp polls

This will create a polls app with standard django app layout:

$ tree.

manage.pypolls

admin.pyapps.py__init__.pymigrations

__init__.pymodels.pytests.pyviews.py

mysite__init__.pysettings.pyurls.pywsgi.py

3 directories, 12 files

And lets add our polls app and django_sorcery in INSTALLED_APPS in mysite/settings.py:

5

Page 10: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','django_sorcery','polls.apps.PollsConfig',

]

Now we’re going to make a twist and start building our app with sqlalchemy. Lets define our models in polls/models.py:

from django_sorcery.db import databases

db = databases.get("default")

class Question(db.Model):pk = db.Column(db.Integer(), autoincrement=True, primary_key=True)question_text = db.Column(db.String(length=200))pub_date = db.Column(db.DateTime())

class Choice(db.Model):pk = db.Column(db.Integer(), autoincrement=True, primary_key=True)choice_text = db.Column(db.String(length=200))votes = db.Column(db.Integer(), default=0)

question = db.ManyToOne(Question, backref=db.backref("choices", cascade="all,→˓delete-orphan"))

Now that we have some models, lets create a migration using alembic integration:

$ python manage.py sorcery revision -m "Add question and poll models" pollsGenerating ./polls/migrations/3983fc419e10_add_question_and_poll_models.py ... done

Let’s take a look at the generated migration file ./polls/migrations/3983fc419e10_add_question_and_poll_models.py:

"""Add question and poll models

Revision ID: 3983fc419e10Revises:Create Date: 2019-04-16 20:57:48.154179"""

from alembic import opimport sqlalchemy as sa

# revision identifiers, used by Alembic.revision = '3983fc419e10'down_revision = None

(continues on next page)

6 Chapter 2. Quick Start

Page 11: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

(continued from previous page)

branch_labels = Nonedepends_on = None

def upgrade():# ### commands auto generated by Alembic - please adjust! ###op.create_table('question',sa.Column('pk', sa.Integer(), autoincrement=True, nullable=False),sa.Column('question_text', sa.String(length=200), nullable=True),sa.Column('pub_date', sa.DateTime(), nullable=True),sa.PrimaryKeyConstraint('pk'))op.create_table('choice',sa.Column('pk', sa.Integer(), autoincrement=True, nullable=False),sa.Column('choice_text', sa.String(length=200), nullable=True),sa.Column('votes', sa.Integer(), nullable=True),sa.Column('question_pk', sa.Integer(), nullable=True),sa.ForeignKeyConstraint(['question_pk'], ['question.pk'], ),sa.PrimaryKeyConstraint('pk'))# ### end Alembic commands ###

def downgrade():# ### commands auto generated by Alembic - please adjust! ###op.drop_table('choice')op.drop_table('question')# ### end Alembic commands ###

Let’s take a look at generated sql:

$ python manage.py sorcery upgrade --sql polls

CREATE TABLE alembic_version_polls (version_num VARCHAR(32) NOT NULL,CONSTRAINT alembic_version_polls_pkc PRIMARY KEY (version_num)

);

-- Running upgrade -> d7d86e07cc8e

CREATE TABLE question (pk INTEGER NOT NULL,question_text VARCHAR(200),pub_date DATETIME,PRIMARY KEY (pk)

);

CREATE TABLE choice (pk INTEGER NOT NULL,choice_text VARCHAR(200),votes INTEGER,question_pk INTEGER,PRIMARY KEY (pk),FOREIGN KEY(question_pk) REFERENCES question (pk)

);

INSERT INTO alembic_version_polls (version_num) VALUES ('d7d86e07cc8e');

7

Page 12: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

Let’s bring our db up to date:

$ python manage.py sorcery upgradeRunning migrations for polls on database default

Right now, we have enough to hop in django shell:

$ python manage.py shell

>>> from polls.models import Choice, Question, db # Import the model classes and the→˓db

# we have no choices or questions in db yet>>> Choice.query.all()[]>>> Question.query.all()[]

# Lets create a new question>>> from django.utils import timezone>>> q = Question(question_text="What's new?", pub_date=timezone.now())>>> qQuestion(pk=None, pub_date=datetime.datetime(2018, 5, 19, 0, 54, 20, 778186, tzinfo=→˓<UTC>), question_text="What's new?")

# lets save our question, we need to add our question to the db>>> db.add(q)

# at this point the question is in pending state>>> db.newIdentitySet([Question(pk=None, pub_date=datetime.datetime(2018, 5, 19, 0, 54, 20,→˓778186, tzinfo=<UTC>), question_text="What's new?")])

# lets flush to the database>>> db.flush()

# at this point our question is in persistent state and will receive a primary key>>> q.pk1

# lets change the question text>>> q.question_text = "What's up?">>> db.flush()

# Question.objects and Question.query are both query properties that return a query→˓object bound to db>>> Question.objects<django_sorcery.db.query.Query at 0x7feb1c7899e8>>>> Question.query<django_sorcery.db.query.Query at 0x7feb1c9377f0>

# and lets see all the questions>>> Question.objects.all()[Question(pk=1, pub_date=datetime.datetime(2018, 5, 19, 0, 54, 20, 778186, tzinfo=→˓<UTC>), question_text="What's up?")]

>>> exit()

Let’s add a couple of views in polls/views.py, starting with a list view:

8 Chapter 2. Quick Start

Page 13: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

from django.shortcuts import renderfrom django.template import loaderfrom django.http import HttpResponseRedirectfrom django.urls import reverse

from django_sorcery.shortcuts import get_object_or_404

from .models import Question, Choice, db

def index(request):latest_question_list = Question.objects.order_by(Question.pub_date.desc())[:5]context = {'latest_question_list': latest_question_list}return render(request, 'polls/index.html', context)

def detail(request, question_id):question = get_object_or_404(Question, pk=question_id)return render(request, 'polls/detail.html', {'question': question})

def results(request, question_id):question = get_object_or_404(Question, pk=question_id)return render(request, 'polls/results.html', {'question': question})

def vote(request, question_id):question = get_object_or_404(Question, pk=question_id)

selected_choice = Choice.query.filter(Choice.question == question,Choice.pk == request.POST['choice'],

).one_or_none()

if not selected_choice:return render(request, 'polls/detail.html', {

'question': question,'error_message': "You didn't select a choice.",

})

selected_choice.votes += 1db.flush()return HttpResponseRedirect(reverse('polls:results', args=(question.pk,)))

and register the view in polls/urls.py:

from django.urls import path

from . import views

app_name = 'polls'urlpatterns = [

path('', views.index, name='index'),path('<int:question_id>/', views.detail, name='detail'),path('<int:question_id>/results', views.results, name='results'),path('<int:question_id>/vote', views.vote, name='vote'),

]

9

Page 14: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

and register the SQLAlchemyMiddleware to provide unit-of-work per request pattern:

MIDDLEWARE = ['django_sorcery.db.middleware.SQLAlchemyMiddleware',# ...

]

and add some templates:

polls/templates/polls/index.html:

{% if latest_question_list %}<ul>{% for question in latest_question_list %}<li><a href="{% url 'polls:detail' question.pk %}">{{ question.question_text }}</a></→˓li>{% endfor %}</ul>{% else %}<p>No polls are available.</p>{% endif %}

polls/templates/polls/detail.html:

<h1>{{ question.question_text }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'polls:vote' question.pk %}" method="post">{% csrf_token %}{% for choice in question.choices %}

<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{→˓choice.pk }}" />

<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />{% endfor %}<input type="submit" value="Vote" /></form>

polls/templates/polls/results.html:

<h1>{{ question.question_text }}</h1>

<ul>{% for choice in question.choices %}

<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}→˓</li>{% endfor %}</ul>

<a href="{% url 'polls:detail' question.pk %}">Vote again?</a>

This is all fine but we can do one better using generic views. Lets adjust our views in polls/views.py:

from django.shortcuts import renderfrom django.http import HttpResponseRedirectfrom django.urls import reverse

from django_sorcery.shortcuts import get_object_or_404

(continues on next page)

10 Chapter 2. Quick Start

Page 15: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

(continued from previous page)

from django_sorcery import views

from .models import Question, Choice, db

class IndexView(views.ListView):template_name = 'polls/index.html'context_object_name = 'latest_question_list'

def get_queryset(self):return Question.objects.order_by(Question.pub_date.desc())[:5]

class DetailView(views.DetailView):model = Questionsession = dbtemplate_name = 'polls/detail.html'

class ResultsView(DetailView):template_name = 'polls/results.html'

def vote(request, question_id):question = get_object_or_404(Question, pk=question_id)

selected_choice = Choice.query.filter(Choice.question == question,Choice.pk == request.POST['choice'],

).one_or_none()

if not selected_choice:return render(request, 'polls/detail.html', {

'question': question,'error_message': "You didn't select a choice.",

})

selected_choice.votes += 1db.flush()return HttpResponseRedirect(reverse('polls:results', args=(question.pk,)))

and adjust the polls/urls.py like:

from django.urls import path

from . import views

app_name = 'polls'urlpatterns = [

path('', views.IndexView.as_view(), name='index'),path('<int:pk>/', views.DetailView.as_view(), name='detail'),path('<int:pk>/results', views.ResultsView.as_view(), name='results'),path('<int:question_id>/vote', views.vote, name='vote'),

]

The default values for template_name and context_object_name are similar to django’s generic views. If

11

Page 16: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

we handn’t defined those the default for template names would’ve been polls/question_detail.html andpolls/question_list.html for the detail and list template names, and question and question_listfor context names for detail and list views.

This is all fine but we can even do one better using a viewset. Lets adjust our views in polls/views.py:

from django.http import HttpResponseRedirectfrom django.urls import reverse, reverse_lazy

from django_sorcery.routers import actionfrom django_sorcery.viewsets import ModelViewSet

from .models import Question, Choice, db

class PollsViewSet(ModelViewSet):model = Questionfields = "__all__"destroy_success_url = reverse_lazy("polls:question-list")

def get_success_url(self):return reverse("polls:question-detail", kwargs={"pk": self.object.pk})

@action(detail=True)def results(self, request, *args, **kwargs):

return self.retrieve(request, *args, **kwargs)

@action(detail=True, methods=["POST"])def vote(self, request, *args, **kwargs):

self.object = self.get_object()

selected_choice = Choice.query.filter(Choice.question == self.object, Choice.pk == request.POST.get("choice")

).one_or_none()

if not selected_choice:context = self.get_detail_context_data(object=self.object)context["error_message"] = "You didn't select a choice."self.action = "retrieve"return self.render_to_response(context)

selected_choice.votes += 1db.flush()return HttpResponseRedirect(reverse("polls:question-results", args=(self.object.

→˓pk,)))

And adjusting our polls/urls.py like:

from django.urls import path, include

from django_sorcery.routers import SimpleRouter

from . import views

router = SimpleRouter()router.register("", views.PollsViewSet)

app_name = "polls"urlpatterns = [path("", include(router.urls))]

12 Chapter 2. Quick Start

Page 17: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

With these changes we’ll have the following urls:

$ ./manage.py run show_urls/polls/ polls.views.PollsViewSet polls:question-list/polls/<pk>/ polls.views.PollsViewSet polls:question-detail/polls/<pk>/delete/ polls.views.PollsViewSet polls:question-destroy/polls/<pk>/edit/ polls.views.PollsViewSet polls:question-edit/polls/<pk>/results/ polls.views.PollsViewSet polls:question-results/polls/<pk>/vote/ polls.views.PollsViewSet polls:question-vote/polls/new/ polls.views.PollsViewSet polls:question-new

This will map the following operations to following actions on the viewset:

Method Path Action Route NameGET /polls/ list question-listPOST /polls/ create question-listGET /polls/new/ new question-newGET /polls/1/ retrieve question-detailPOST /polls/1/ update question-detailPUT /polls/1/ update question-detailPATCH /polls/1/ update question-detailDELETE /polls/1/ destroy question-detailGET /polls/1/edit/ edit question-editGET /polls/1/delete/ confirm_destoy question-deletePOST /polls/1/delete/ destroy question-delete

Now, lets add an inline formset to be able to add choices to questions, adjust polls/views.py:

from django.http import HttpResponseRedirectfrom django.urls import reverse, reverse_lazy

from django_sorcery.routers import actionfrom django_sorcery.viewsets import ModelViewSetfrom django_sorcery.formsets import inlineformset_factory

from .models import Question, Choice, db

ChoiceFormSet = inlineformset_factory(relation=Question.choices, fields=(Choice.→˓choice_text.key,), session=db)

class PollsViewSet(ModelViewSet):model = Questionfields = (Question.question_text.key, Question.pub_date.key)destroy_success_url = reverse_lazy("polls:question-list")

def get_success_url(self):return reverse("polls:question-detail", kwargs={"pk": self.object.pk})

def get_form_context_data(self, **kwargs):kwargs["choice_formset"] = self.get_choice_formset()return super().get_form_context_data(**kwargs)

def get_choice_formset(self, instance=None):if not hasattr(self, "_choice_formset"):

(continues on next page)

13

Page 18: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

(continued from previous page)

instance = instance or self.objectself._choice_formset = ChoiceFormSet(

instance=instance, data=self.request.POST if self.request.POST else→˓None

)

return self._choice_formset

def process_form(self, form):if form.is_valid() and self.get_choice_formset(instance=form.instance).is_

→˓valid():return self.form_valid(form)

return form.invalid(self, form)

def form_valid(self, form):self.object = form.save()self.object.choices = self.get_choice_formset().save()db.flush()return HttpResponseRedirect(self.get_success_url())

@action(detail=True)def results(self, request, *args, **kwargs):

return self.retrieve(request, *args, **kwargs)

@action(detail=True, methods=["POST"])def vote(self, request, *args, **kwargs):

self.object = self.get_object()

selected_choice = Choice.query.filter(Choice.question == self.object, Choice.pk == request.POST.get("choice")

).one_or_none()

if not selected_choice:context = self.get_detail_context_data(object=self.object)context["error_message"] = "You didn't select a choice."self.action = "retrieve"return self.render_to_response(context)

selected_choice.votes += 1db.flush()return HttpResponseRedirect(reverse("polls:question-results", args=(self.object.

→˓pk,)))

And add choice_formset in the polls/templates/question_edit.html and polls/templates/question_edit.html

<form ... >...{{ choice_formset }}...

</form >

14 Chapter 2. Quick Start

Page 19: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

2.1 Changelog

2.1.1 0.11.3 (2021-11-30)

• [pre-commit.ci] pre-commit autoupdate (#162) [Serkan Hosca, pre- commit-ci[bot], pre-commit-ci[bot]]

2.1.2 0.11.2 (2021-04-08)

• Django 3.2 support (#159) [Serkan Hosca]

2.1.3 0.11.1 (2021-03-20)

• Attempt django like order by only when all criterion are strings (#158) [Serkan Hosca]

2.1.4 0.11.0 (2021-03-20)

• Add sqlalchemy 1.4 support (#157) [Serkan Hosca]

• Github actions build badge (#155) [Serkan Hosca]

• Adding github actions (#154) [Serkan Hosca]

• Fix build link. [Serkan Hosca]

• Add dj3.1 to matrix (#153) [Serkan Hosca]

• Pre-commit imporanize pyupgrade and docformat (#152) [Serkan Hosca]

• Add django3 to build matrix (#151) [Serkan Hosca]

2.1.5 0.10.2 (2019-11-07)

• Adding check-manifest in pre-commit (#150) [Miroslav Shubernetskiy]

2.1.6 0.10.1 (2019-08-31)

• Drop py2 from setup.py. [Serkan Hosca]

2.1.7 0.10.0 (2019-08-31)

• Drop py2 support (#149) [Serkan Hosca]

• Make model meta look like django meta (#148) [Serkan Hosca]

• Simplify column meta info (#147) [Serkan Hosca]

• Fix ModelChoiceField.get_object and make ModelForm inherit BaseModelForm (#146) [Serkan Hosca]

2.1. Changelog 15

Page 20: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

2.1.8 0.9.4 (2019-07-14)

• Fix middleware response return (#143) [Serkan Hosca]

• Use python/black (#141) [Serkan Hosca]

2.1.9 0.9.3 (2019-06-27)

• Defining test matrix in tox and switchint to tox-travis (#140) [Miroslav Shubernetskiy]

• Increase build matrix (#139) [Serkan Hosca]

• Update pre-commit (#138) [Serkan Hosca]

2.1.10 0.9.2 (2019-05-10)

• Drop trailing zeros on float to decimal conversion (#137) [Serkan Hosca]

2.1.11 0.9.1 (2019-04-28)

• Track committed models (#136) [Serkan Hosca]

• Fix topic. [Serkan Hosca]

2.1.12 0.9.0 (2019-04-23)

• Trigger configure_mappers before commands (#135) [Serkan Hosca]

• Add migrations on tutorial (#134) [Serkan Hosca]

• Drop sqlalchemy init django dependency (#133) [Serkan Hosca]

• Drop deprecated functions (#132) [Serkan Hosca]

• Raising in middleware on error (#131) [Miroslav Shubernetskiy]

• Allow limit_choices_to to be callable (#130) [Serkan Hosca]

• Add a bunch of docs and fix lint issues (#129) [Serkan Hosca]

2.1.13 0.8.12 (2019-03-15)

• Fix field run_validator (#128) [Serkan Hosca]

2.1.14 0.8.11 (2019-02-15)

• Fix db operations import from django for db ranges (#127) [Serkan Hosca]

• Adding black badge (#126) [Miroslav Shubernetskiy]

2.1.15 0.8.10 (2019-02-06)

• Fixing test_site to allow to create test migrations (#125) [Miroslav Shubernetskiy]

16 Chapter 2. Quick Start

Page 21: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

2.1.16 0.8.9 (2019-02-05)

• Adding default maxlength/min/maxvalue validators to CharField/IntField (#124) [Miroslav Shubernetskiy]

• Include migration mako script (#123) [Serkan Hosca]

2.1.17 0.8.8 (2019-01-29)

• Raise validation error with field name on coersion (#121) [Serkan Hosca]

• Add docs for testing. [Serkan Hosca]

2.1.18 0.8.7 (2019-01-26)

• Add autogenerate foreign key indexes (#118) [Serkan Hosca]

• Adding Transact testing utility with transact pytest fixture (#119) [Miroslav Shubernetskiy]

2.1.19 0.8.6 (2019-01-11)

• Added signals for create_all and drop_all (#117) [Miroslav Shubernetskiy]

2.1.20 0.8.5 (2019-01-10)

• Fixing composite field validation (#116) [Miroslav Shubernetskiy]

2.1.21 0.8.4 (2019-01-09)

• Adding OneToOne relationship shortcut (#115) [Miroslav Shubernetskiy]

2.1.22 0.8.3 (2019-01-08)

• Validate only pre-loaded models (#114) [Miroslav Shubernetskiy]

2.1.23 0.8.2 (2019-01-04)

• Fix decimal cleaning with thousand separator (#113) [Serkan Hosca]

2.1.24 0.8.1 (2019-01-04)

• Split choice from enum column info (#111) [Serkan Hosca]

• Regenerate docs. [Serkan Hosca]

2.1.25 0.8.0 (2019-01-02)

• Refactor coercers (#110) [Serkan Hosca]

• Added django-like filtering support to Query (#108) [Miroslav Shubernetskiy]

2.1. Changelog 17

Page 22: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

2.1.26 0.7.7 (2018-12-11)

• Make statement recording optional (#107) [Serkan Hosca]

2.1.27 0.7.6 (2018-12-10)

• Add query recording to profiler (#106) [Serkan Hosca]

2.1.28 0.7.5 (2018-12-04)

• Fix field column naming (#105) [Serkan Hosca]

• Parallel resetdb (#104) [Serkan Hosca]

• Refactor full_clean validation (#103) [Serkan Hosca]

2.1.29 0.7.4 (2018-11-29)

• Add validation runner and refactor validation (#102) [Serkan Hosca]

2.1.30 0.7.3 (2018-11-28)

• Fix event deque mutation (#101) [Serkan Hosca]

2.1.31 0.7.2 (2018-11-25)

• Add more tests (#100) [Serkan Hosca]

2.1.32 0.7.1 (2018-11-24)

• Fix boolean field constraint name (#99) [Serkan Hosca]

• Meta docs and more meta usage (#98) [Serkan Hosca]

• Nicer meta reprs (#97) [Serkan Hosca]

2.1.33 0.7.0 (2018-11-23)

• Refactor formfield mapping (#95) [Serkan Hosca]

2.1.34 0.6.18 (2018-11-20)

• Added full_clean(recursive=True) for adhoc full tree validation (#96) [Miroslav Shubernetskiy]

2.1.35 0.6.17 (2018-11-19)

• Implement formfield support in fields (#93) [Serkan Hosca]

• Remove yapf config. [Serkan Hosca]

18 Chapter 2. Quick Start

Page 23: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

2.1.36 0.6.16 (2018-11-16)

• Fix docs build. [Serkan Hosca]

• Add TimestampField (#74) [Serkan Hosca]

2.1.37 0.6.15 (2018-11-14)

• Fix edge case with enum field (#69) [Serkan Hosca]

2.1.38 0.6.14 (2018-11-14)

• Refactor autocoercers to allow coerce individual attrs (#68) [Serkan Hosca]

• Bump pre-commit check versions (#67) [Serkan Hosca]

• Caching pip and pre-commit. [Miroslav Shubernetskiy]

• Tiny fixup (#65) [Anthony Sottile]

2.1.39 0.6.13 (2018-11-08)

• Fixing DecimalField not honoring max_digits and decimal_places (#64) [Miroslav Shubernetskiy]

2.1.40 0.6.12 (2018-11-07)

• Allowing to set if field is required separately from nullable (#63) [Miroslav Shubernetskiy]

• Fix coercer issues (#62) [Serkan Hosca]

2.1.41 0.6.11 (2018-11-05)

• Implement autocoerce using form fields (#61) [Serkan Hosca]

• Update lock. [Serkan Hosca]

• Adding more validators (#60) [Miroslav Shubernetskiy]

2.1.42 0.6.10 (2018-10-31)

• List primary keys directly (#59) [Serkan Hosca]

• Passing model-defined validators to field_kwargs (#58) [Miroslav Shubernetskiy]

• Ignoring schema names in alembic version table for sqlite (#57) [Miroslav Shubernetskiy]

2.1.43 0.6.9 (2018-10-17)

• Not running field validations when column has default value (#56) [Miroslav Shubernetskiy]

2.1. Changelog 19

Page 24: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

2.1.44 0.6.8 (2018-10-16)

• Rename OPTIONS to ALCHEMY_OPTIONS (#55) [Serkan Hosca]

• Relock (#54) [Serkan Hosca]

2.1.45 0.6.7 (2018-10-03)

• Allowing to customize whether to log or add headers in profiler (#53) [Miroslav Shubernetskiy]

2.1.46 0.6.6 (2018-09-27)

• Merge pull request #51 from shosca/fields. [Serkan Hosca]

• Django-like fields. [Serkan Hosca]

2.1.47 0.6.5 (2018-09-21)

• Merge pull request #52 from shosca/engine_options. [Serkan Hosca]

• Support for more engine options in url. [Miroslav Shubernetskiy]

2.1.48 0.6.4 (2018-09-18)

• Merge pull request #49 from shosca/deserialize. [Serkan Hosca]

• Added tests for relation_info. [Miroslav Shubernetskiy]

• Using local_remote_pairs_for_identity_key to backfill models relations in deserialize. [Miroslav Shubernetskiy]

• Try backpopulate by fk’s on deserialize. [Serkan Hosca]

• Deserialize model instance. [Serkan Hosca]

• Merge pull request #50 from shosca/refactor-fieldmapper. [Serkan Hosca]

• Refactor field mapping. [Serkan Hosca]

2.1.49 0.6.3 (2018-09-04)

• Merge pull request #48 from shosca/url. [Serkan Hosca]

• Only popping custom engine parameters from url. [Miroslav Shubernetskiy]

2.1.50 0.6.2 (2018-08-31)

• Merge pull request #47 from shosca/signals. [Serkan Hosca]

• Fix profile middleware bug by lazily attaching signals. [Miroslav Shubernetskiy]

20 Chapter 2. Quick Start

Page 25: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

2.1.51 0.6.1 (2018-08-28)

• Merge pull request #46 from shosca/query-options. [Serkan Hosca]

• Add get query options. [Serkan Hosca]

• Merge pull request #45 from shosca/profiler-middleware. [Serkan Hosca]

• Start/stop in profiler middleware. [Serkan Hosca]

2.1.52 0.6.0 (2018-08-25)

• Merge pull request #40 from shosca/alembic. [Serkan Hosca]

• Fixing import issue after rebase. [Miroslav Shubernetskiy]

• Fixing test_sql not expecting “Running migrations. . . ” messages. [Miroslav Shubernetskiy]

• Not printing “Running migrations. . . ” message when –sql is used. [Miroslav Shubernetskiy]

• Removing import hook. instead adding alembic_app_created signal. [Miroslav Shubernetskiy]

• Checking if migrations are present before configuring alembic. [Miroslav Shubernetskiy]

• Renaming makemigrations to revision and importing migrations.__init__ [Miroslav Shubernetskiy]

• Matching parameters to alembic and minor improvements. [Miroslav Shubernetskiy]

• Added –no-color to all ./manage.py sorcery command in tests. [Miroslav Shubernetskiy]

• Added SQLAlchemy.models_registry. [Miroslav Shubernetskiy]

• Add alembic support. [Serkan Hosca]

• Added prefix to composite columns constraint names. [Miroslav Shubernetskiy]

• Added way to customize metadata options via config. (#43) [Miroslav Shubernetskiy]

• Run tests on pg (#42) [Serkan Hosca]

2.1.53 0.5.5 (2018-07-28)

• Fix scoped session proxying (#41) [Serkan Hosca]

2.1.54 0.5.4 (2018-07-19)

• Adding profiler with middleware and pytest plugin (#39) [Miroslav Shubernetskiy]

2.1.55 0.5.3 (2018-07-18)

• Multi db transaction (#36) [Serkan Hosca]

2.1.56 0.5.2 (2018-07-17)

• Added sane CompositeBase.__bool__ which checks all attributes (#38) [Miroslav Shubernetskiy]

2.1. Changelog 21

Page 26: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

2.1.57 0.5.1 (2018-07-16)

• Allowing to specify via env var some engine options (#37) [Miroslav Shubernetskiy]

2.1.58 0.5.0 (2018-07-05)

• Add namespaced command (#35) [Serkan Hosca]

• Fix unique validator and add declare last signal (#34) [Serkan Hosca]

2.1.59 0.4.13 (2018-07-03)

• Fix unique column validator (#32) [Serkan Hosca]

• Refactored all relations to separate module. also moving declare_first as signal (#31) [Miroslav Shubernetskiy]

2.1.60 0.4.12 (2018-06-30)

• Fix packaging. [Serkan Hosca]

2.1.61 0.4.11 (2018-06-30)

• Snakify table names (#30) [Serkan Hosca]

2.1.62 0.4.10 (2018-06-28)

• Add Unique validator (#29) [Serkan Hosca]

2.1.63 0.4.9 (2018-06-26)

• Fix init kwargs (#28) [Serkan Hosca]

• Add composite cloning and serialization (#27) [Serkan Hosca]

2.1.64 0.4.8 (2018-06-23)

• Add docs (#26) [Serkan Hosca]

• Wire up form to do model clean (#25) [Serkan Hosca]

2.1.65 0.4.7 (2018-06-23)

• Drop drf dependency (#24) [Serkan Hosca]

2.1.66 0.4.6 (2018-06-22)

• Added CompositeField and all related goodies (#23) [Miroslav Shubernetskiy]

22 Chapter 2. Quick Start

Page 27: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

2.1.67 0.4.5 (2018-06-14)

• Merge pull request #22 from shosca/config_refactor. [Serkan Hosca]

• Pass along kwargs with custom sqla class. [Serkan Hosca]

2.1.68 0.4.4 (2018-06-13)

• Merge pull request #21 from shosca/config_refactor. [Serkan Hosca]

• Grab only custom sqla class from config. [Serkan Hosca]

2.1.69 0.4.3 (2018-06-09)

• Merge pull request #20 from shosca/config_refactor. [Serkan Hosca]

• Remove engine hacks and refactor config for custom sqla class. [Serkan Hosca]

2.1.70 0.4.2 (2018-06-04)

• 0.4.2. [Serkan Hosca]

• Merge pull request #19 from shosca/inlineformset. [Serkan Hosca]

• Inline formsets. [Serkan Hosca]

2.1.71 0.4.1 (2018-05-31)

• 0.4.1. [Serkan Hosca]

• Merge pull request #18 from shosca/docs. [Serkan Hosca]

• Add more docs for viewsets. [Serkan Hosca]

2.1.72 0.4.0 (2018-05-31)

• 0.4.0. [Serkan Hosca]

• Add basic viewset support. [Serkan Hosca]

2.1.73 0.3.3 (2018-05-21)

• 0.3.3. [Serkan Hosca]

• Merge pull request #15 from shosca/middleware-logger. [Serkan Hosca]

• Add middleware logger. [Serkan Hosca]

• Merge pull request #14 from shosca/docs. [Serkan Hosca]

• More docs. [Serkan Hosca]

• Merge pull request #13 from shosca/docs. [Serkan Hosca]

• Add a test_site and docs. [Serkan Hosca]

2.1. Changelog 23

Page 28: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

2.1.74 0.3.2 (2018-05-17)

• 0.3.2. [Serkan Hosca]

• Merge pull request #12 from shosca/middleware. [Serkan Hosca]

• Refactor middleware. [Serkan Hosca]

2.1.75 0.3.1 (2018-05-17)

• 0.3.1. [Serkan Hosca]

• Merge pull request #11 from shosca/shortcuts. [Serkan Hosca]

• Add get_list_or_404 shortcut. [Serkan Hosca]

• Add get_object_or_404 shortcut. [Serkan Hosca]

2.1.76 0.3.0 (2018-05-16)

• 0.3.0. [Serkan Hosca]

• Merge pull request #10 from shosca/url-refactory. [Serkan Hosca]

• Refactor url generation and allow query settings. [Serkan Hosca]

2.1.77 0.2.8 (2018-05-14)

• 0.2.8. [Serkan Hosca]

• Merge pull request #9 from shosca/refactor-enum. [Serkan Hosca]

• Refactor enum field. [Serkan Hosca]

2.1.78 0.2.7 (2018-05-12)

• 0.2.7. [Serkan Hosca]

• Merge pull request #8 from shosca/enum-field. [Serkan Hosca]

• Enum field fixes. [Serkan Hosca]

2.1.79 0.2.6 (2018-05-09)

• 0.2.6. [Serkan Hosca]

• Merge pull request #7 from shosca/middeware-signals. [Serkan Hosca]

• Add middleware signals. [Serkan Hosca]

24 Chapter 2. Quick Start

Page 29: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

2.1.80 0.2.5 (2018-05-09)

• 0.2.5. [Serkan Hosca]

• Merge pull request #6 from shosca/lazy-init. [Serkan Hosca]

• Lazy create engine. [Serkan Hosca]

2.1.81 0.2.4 (2018-05-08)

• 0.2.4. [Serkan Hosca]

• Merge pull request #5 from shosca/field-map. [Serkan Hosca]

• Use mro in python_type field mapping. [Serkan Hosca]

2.1.82 0.2.3 (2018-05-08)

• 0.2.3. [Serkan Hosca]

2.1.83 0.2.2 (2018-05-08)

• 0.2.2. [Serkan Hosca]

• Merge pull request #4 from shosca/app-label-template. [Serkan Hosca]

• Use app config label in template name. [Serkan Hosca]

2.1.84 0.2.1 (2018-05-07)

• 0.2.1. [Serkan Hosca]

• Merge pull request #3 from shosca/transaction. [Serkan Hosca]

• Add transaction tests. [Serkan Hosca]

• Merge pull request #2 from shosca/proxy. [Serkan Hosca]

• Refactor scoped session proxy. [Serkan Hosca]

• Merge pull request #1 from shosca/field-mapping. [Serkan Hosca]

• More field mapping coverage. [Serkan Hosca]

2.1.85 0.2.0 (2018-05-07)

Fix

• Model choice field iterator. [Serkan Hosca]

2.1. Changelog 25

Page 30: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

Other

• 0.2.0. [Serkan Hosca]

• Increase test coverage. [Serkan Hosca]

• Increase test coverage. [Serkan Hosca]

2.1.86 0.1.1 (2018-05-05)

• Fix meta test. [Serkan Hosca]

2.1.87 0.1.0 (2018-05-05)

• Initial commit. [Serkan Hosca]

2.2 API Documentation

2.2.1 django_sorcery

django_sorcery package

Subpackages

django_sorcery.db package

Package with SQLAlchemy abstractions to interact with the database. All tools implemented here assume unit-of-workusage pattern.

Connecting

Connecting to the DB is as simple as using a url with SQLAlchemy abstraction:

>>> from django_sorcery.db import SQLAlchemy>>> db = SQLAlchemy('sqlite://')

You can also use an alias to connect to a database as well. Just like Django’s DATABASES, connection settings foraliases are stored in SQLALCHEMY_CONNECTIONS. As such all databases are referred by their aliases just like inDjango ORM. For example "default" is an alias to the default connect:

>>> db = SQLAlchemy('default')

ORM Goodies

SQLAlchemy is itself also a threadlocal manager that proxies calls to a thread local Session instance and providesa couple of shortcuts when interacting with SQLAlchemy session. To have them installed, you can subclass from thedeclarative base generated by the DB. In addition SQLAlchemy also exposes most of SQLALchemy’s elements so asingle import should suffice to define most tables:

26 Chapter 2. Quick Start

Page 31: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

>>> class BarModel(db.Model):... id = db.Column(db.Integer(), primary_key=True)

>>> class FooModel(db.Model):... id = db.Column(db.Integer(), primary_key=True)... id2 = db.Column(db.Integer(), primary_key=True)... name = db.Column(db.String(length=32))... bar_id = db.Column(db.Integer(), db.ForeignKey(BarModel.id, name='FK_foo_bar',→˓ use_alter=True))... bar = db.relationship(BarModel)

>>> db.create_all()

Doing so will allow to use a couple of useful shortcuts:

Query.get():

Identity map in SQLAlchemy is amazing. Composite keys not so much. Put them together is even worse.SQLAlchemy uses a special session which allows keyword arguments when using .get(). It is muchmore explicit and is less error-prone as SQLAlchemy’s default implementation expects only positionalarguments where order of primary keys matters. For example:

>>> db.query(FooModel).get(id=123, id2=456)

SQLAlchemy.queryproperty():

Allows to create a property which will normalize to a query object of the model. It will use the correctsession within the transaction so no need to pass session around. For example:

>>> class MyView(object):... queryset = db.queryproperty(FooModel)

You can even pass default filtering criteria if needed:

>>> class MyView(object):... queryset = db.queryproperty(FooModel, to_be_deleted=False)

In addition this pattern can be used to implement Django’s ORM style model managers:

>>> class UserModel(db.Model):... id = db.Column(db.Integer(), primary_key=True)... username = db.Column(db.String())... is_active = db.Column(db.Boolean())...... objects = db.queryproperty()... active = db.queryproperty(is_active=True)

That can be used directly:

>>> UserModel.metadata.create_all(bind=db.engine)>>> db.add_all([... UserModel(id=1, username='foo', is_active=False),... UserModel(id=2, username='bar', is_active=True),... ])>>> db.flush()

>>> UserModel.objects.all()[UserModel(id=1, is_active=False, username='foo'), UserModel(id=2, is_→˓active=True, username='bar')] (continues on next page)

2.2. API Documentation 27

Page 32: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

(continued from previous page)

>>> UserModel.active.all()[UserModel(id=2, is_active=True, username='bar')]

This pattern is very useful when combined with Django style views:

>>> class MyView(object):... queryset = UserModel.active

>>> MyView().queryset.all()[UserModel(id=2, is_active=True, username='bar')]

Additional filters/options can be applied as well:

>>> class MyView(object):... queryset = UserModel.active.filter(UserModel.username == 'test')

>>> MyView().queryset.all()[]

Transactions

If you need to explicitly use transactions, you can use SQLAlchemy.atomic():

>>> with db.atomic(savepoint=False):... _ = db.query(UserModel).filter_by(username='hello').update(dict(username=→˓'world'))

>>> @db.atomic(savepoint=False)... def do_something():... db.query(UserModel).filter_by(username='hello').update(username='world')

Warning: You better know what you are doing if you need this. If you are not, sure, JUST USE THE MIDDLE-WARE (see below).

Django

To complete the unit-of-work SQLAlchemy ships with capability to generate Django middleware to commit at theend of the request for the used session within the request:

# settings.py>>> MIDDLEWARE = [... # should be last in response life-cycle... # or first in middleware list... 'path.to.db.middleware',... # rest of middleware... ]

Subpackages

28 Chapter 2. Quick Start

Page 33: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

django_sorcery.db.alembic package

Submodules

django_sorcery.db.alembic.base module

Default alembic config things.

django_sorcery.db.alembic.base.setup_config(config)The default alembic config created handler.

django_sorcery.db.alembic.signals module

Default alembic signal configuration.

django_sorcery.db.alembic.signals.include_object(obj, name, type_, reflected, com-pare_to)

The default include_object handler for alembic, delegates to alembic_include_object signal.

The return value will be considered True if all the signal handlers return True for the object to be included inmigration.

django_sorcery.db.alembic.signals.process_revision_directives(context, revision,directives)

The default process_revision_directives handler for alembic, delegates to alembic_process_revision_directives.

django_sorcery.db.meta package

Submodules

django_sorcery.db.meta.base module

Base model metadata things.

class django_sorcery.db.meta.base.model_info_metaBases: type

Model metadata singleton.

django_sorcery.db.meta.column module

Django-esque field metadata and interface providers.

class django_sorcery.db.meta.column.boolean_column_info(column, prop=None, par-ent=None, name=None)

Bases: django_sorcery.db.meta.column.column_info

Provides meta info for boolean columns.

to_python(value)Convert input value to appropriate python object.

class django_sorcery.db.meta.column.choice_column_info(column, prop=None, par-ent=None, name=None)

Bases: django_sorcery.db.meta.column.column_info

2.2. API Documentation 29

Page 34: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

Provides meta info for enum columns with simple choices.

default_form_classalias of django.forms.fields.TypedChoiceField

to_python(value)Convert input value to appropriate python object.

class django_sorcery.db.meta.column.column_info(column, prop=None, parent=None,name=None)

Bases: object

A helper class that makes sqlalchemy property and column inspection easier.

attname

attribute

choices

clean(value, instance)Convert the value’s type and run validation.

Validation errors from to_python() and validate() are propagated. Return the correct value if no error israised.

coercerForm field to be used to coerce data types.

column

default

default_error_messages = {'blank': 'This field cannot be blank.', 'invalid_choice': 'Value %(value)r is not a valid choice.', 'null': 'This field cannot be null.', 'unique': '%(model_name)s with this %(field_label)s already exists.', 'unique_for_date': '%(field_label)s must be unique for %(date_field_label)s %(lookup_type)s.'}

default_form_class = None

empty_values

error_messages

field_kwargs

form_class

formfield(form_class=None, **kwargs)Returns the form field for the field.

help_text

is_relation = False

label

name

null

parent

parent_model

property

required

run_validators(value)Run field’s validators and raise ValidationError if necessary.

30 Chapter 2. Quick Start

Page 35: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

to_python(value)Convert input value to appropriate python object.

unique

validate(value, instance)Validate value and raise ValidationError if necessary.

validators

widget

class django_sorcery.db.meta.column.date_column_info(column, prop=None, par-ent=None, name=None)

Bases: django_sorcery.db.meta.column.column_info

Provides meta info for date columns.

coercerForm field to be used to coerce data types.

default_form_classalias of django.forms.fields.DateField

to_python(value)Convert input value to appropriate python object.

class django_sorcery.db.meta.column.datetime_column_info(column, prop=None, par-ent=None, name=None)

Bases: django_sorcery.db.meta.column.column_info

Provides meta info for datetime columns.

coercerForm field to be used to coerce data types.

default_form_classalias of django.forms.fields.DateTimeField

to_python(value)Convert input value to appropriate python object.

class django_sorcery.db.meta.column.enum_column_info(column, prop=None, par-ent=None, name=None)

Bases: django_sorcery.db.meta.column.choice_column_info

Provides meta info for enum columns with Enum choices.

default_form_classalias of django_sorcery.fields.EnumField

to_python(value)Convert input value to appropriate python object.

class django_sorcery.db.meta.column.float_column_info(column, prop=None, par-ent=None, name=None)

Bases: django_sorcery.db.meta.column.column_info

Provides meta info for float columns.

default_form_classalias of django.forms.fields.FloatField

to_python(value)Convert input value to appropriate python object.

2.2. API Documentation 31

Page 36: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

class django_sorcery.db.meta.column.integer_column_info(column, prop=None, par-ent=None, name=None)

Bases: django_sorcery.db.meta.column.column_info

Provides meta info for integer columns.

default_form_classalias of django.forms.fields.IntegerField

to_python(value)Convert input value to appropriate python object.

class django_sorcery.db.meta.column.interval_column_info(column, prop=None, par-ent=None, name=None)

Bases: django_sorcery.db.meta.column.column_info

Provides meta info for interval columns.

default_form_classalias of django.forms.fields.DurationField

to_python(value)Convert input value to appropriate python object.

class django_sorcery.db.meta.column.numeric_column_info(column, prop=None, par-ent=None, name=None)

Bases: django_sorcery.db.meta.column.column_info

Provides meta info for numeric columns.

decimal_places

default_form_classalias of django.forms.fields.DecimalField

max_digits

to_python(value)Convert input value to appropriate python object.

class django_sorcery.db.meta.column.string_column_info(column, prop=None, par-ent=None, name=None)

Bases: django_sorcery.db.meta.column.column_info

Provides meta info for string columns.

default_form_classalias of django.forms.fields.CharField

to_python(value)Convert input value to appropriate python object.

class django_sorcery.db.meta.column.text_column_info(column, prop=None, par-ent=None, name=None)

Bases: django_sorcery.db.meta.column.string_column_info

Provides meta info for text columns.

class django_sorcery.db.meta.column.time_column_info(column, prop=None, par-ent=None, name=None)

Bases: django_sorcery.db.meta.column.column_info

Provides meta info for time columns.

default_form_classalias of django.forms.fields.TimeField

32 Chapter 2. Quick Start

Page 37: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

to_python(value)Convert input value to appropriate python object.

django_sorcery.db.meta.composite module

Metadata for composite sqlalchemy properties.

class django_sorcery.db.meta.composite.composite_info(composite, parent=None)Bases: object

A helper class that makes sqlalchemy composite model inspection easier.

attributeReturns composite field instrumented attribute for generating query expressions.

clean_fields(instance, exclude=None)Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur.

field_namesReturns field names used in composite.

full_clean(instance, exclude=None)Call clean_fields(), clean(), and run_validators() on the composite model.

Raise a ValidationError for any errors that occur.

model_classReturns the composite class.

nameReturns composite field name.

parent

parent_modelReturns the model class that the attribute belongs to.

prop

properties

run_validators(instance)Run composite field’s validators and raise ValidationError if necessary.

django_sorcery.db.meta.model module

Metadata for sqlalchemy models.

django_sorcery.db.meta.model.Identityalias of django_sorcery.db.meta.model.Key

class django_sorcery.db.meta.model.model_info(model)Bases: object

A helper class that makes sqlalchemy model inspection easier.

app_config

app_label

clean_fields(instance, exclude=None, **kwargs)Clean all fields on object.

2.2. API Documentation 33

Page 38: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

clean_nested_fields(instance, exclude=None, **kwargs)Clean all nested fields which includes composites.

clean_relation_fields(instance, exclude=None, **kwargs)Clean all relation fields.

column_properties

composites

concrete_fields

field_names

fields

full_clean(instance, exclude=None, **kwargs)Run model’s full clean chain.

This will run all of these in this order:

• will validate all columns by using clean_<column> methods

• will validate all nested objects (e.g. composites) with full_clean

• will run through all registered validators on validators attribute

• will run full model validation with self.clean()

• if recursive kwarg is provided, will recursively clean all relations. Useful when all models needto be explicitly cleaned without flushing to DB.

get_field(field_name)

get_key(instance)Returns the primary key tuple from the instance

identity_key_from_dict(kwargs)Returns identity key from a dictionary for the given model.

identity_key_from_instance(instance)Returns the primary key tuple from the instance

label

label_lower

local_fields

mapper

model

model_class

model_name

object_name

opts

ordering

primary_keys

primary_keys_from_dict(kwargs)Returns the primary key tuple from a dictionary to be used in a sqlalchemy query.get() call.

34 Chapter 2. Quick Start

Page 39: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

primary_keys_from_instance(instance)Return a dict containing the primary keys of the instance

private_fields

properties

relationships

run_validators(instance, exclude=None, **kwargs)Check all model validators registered on validators attribute.

sa_state(instance)Returns sqlalchemy instance state.

unique_together

verbose_name

verbose_name_plural

django_sorcery.db.meta.relations module

Metadata for sqlalchemy model relationships.

class django_sorcery.db.meta.relations.relation_info(relationship)Bases: object

A helper class that makes sqlalchemy relationship property inspection easier.

attribute

direction

field_kwargs

foreign_keys

formfield(form_class=None, **kwargs)

get_form_class()

local_remote_pairs

local_remote_pairs_for_identity_key

name

parent_mapper

parent_model

parent_table

related_mapper

related_model

related_table

relationship

uselist

2.2. API Documentation 35

Page 40: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

Submodules

django_sorcery.db.composites module

Support for reusable sqlalchemy composite fields.

class django_sorcery.db.composites.BaseComposite(*args, **kwargs)Bases: object

Base class for creating composite classes which CompositeField will understand.

For example:

class MyComposite(object):foo = db.Column(db.Integer())bar = db.Column(db.Integer())

class MyModel(db.Model):test = db.CompositeField(MyComposite)# both test_foo and test_bar columns will be added to model# their instrumented properties will be _test_foo and _test_bar

as_dict()Serializer composite to a dictionary.

class django_sorcery.db.composites.CompositeField(class_, **kwargs)Bases: sqlalchemy.orm.descriptor_props.CompositeProperty

Composite field which understands composite objects with builtin columns.

See BaseComposite for examples.

instrument_class(mapper)Hook called by the Mapper to the property to initiate instrumentation of the class attribute managed bythis MapperProperty.

The MapperProperty here will typically call out to the attributes module to set up an InstrumentedAt-tribute.

This step is the first of two steps to set up an InstrumentedAttribute, and is called early in the mappersetup process.

The second step is typically the init_class_attribute step, called from StrategizedProperty via thepost_instrument_class() hook. This step assigns additional state to the InstrumentedAttribute (specificallythe “impl”) which has been determined after the MapperProperty has determined what kind of persistencemanagement it needs to do (e.g. scalar, object, collection, etc).

django_sorcery.db.fields module

Django-esque declarative fields for sqlalchemy.

class django_sorcery.db.fields.BigIntegerField(*args, **kwargs)Bases: django_sorcery.db.fields.ValidateIntegerFieldMixin, django_sorcery.db.fields.Field

Django like big integer field.

default_validators = [<function validate_integer>]

36 Chapter 2. Quick Start

Page 41: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

form_classalias of django.forms.fields.IntegerField

type_classalias of sqlalchemy.sql.sqltypes.BigInteger

class django_sorcery.db.fields.BinaryField(*args, **kwargs)Bases: django_sorcery.db.fields.Field

Django like binary field.

length_is_required = False

type_classalias of sqlalchemy.sql.sqltypes.LargeBinary

class django_sorcery.db.fields.BooleanField(*args, **kwargs)Bases: django_sorcery.db.fields.Field

Django like boolean field.

form_classalias of django.forms.fields.BooleanField

get_column_kwargs(kwargs)Returns sqlalchemy column kwargs.

get_type_kwargs(type_class, kwargs)Returns sqlalchemy type kwargs.

type_classalias of sqlalchemy.sql.sqltypes.Boolean

class django_sorcery.db.fields.CharField(*args, **kwargs)Bases: django_sorcery.db.fields.Field

Django like char field.

form_classalias of django.forms.fields.CharField

get_type_kwargs(type_class, kwargs)Returns sqlalchemy type kwargs.

get_validators(validators)Returns django validators for the field.

length_is_required = True

type_classalias of sqlalchemy.sql.sqltypes.String

class django_sorcery.db.fields.DateField(*args, **kwargs)Bases: django_sorcery.db.fields.Field

Django like date field.

form_classalias of django.forms.fields.DateField

type_classalias of sqlalchemy.sql.sqltypes.Date

class django_sorcery.db.fields.DateTimeField(*args, **kwargs)Bases: django_sorcery.db.fields.Field

2.2. API Documentation 37

Page 42: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

Django like datetime field.

form_classalias of django.forms.fields.DateTimeField

type_classalias of sqlalchemy.sql.sqltypes.DateTime

class django_sorcery.db.fields.DecimalField(*args, **kwargs)Bases: django_sorcery.db.fields.Field

Django like decimal field.

form_classalias of django.forms.fields.DecimalField

get_type_kwargs(type_class, kwargs)Returns sqlalchemy type kwargs.

get_validators(validators)Returns django validators for the field.

type_classalias of sqlalchemy.sql.sqltypes.Numeric

class django_sorcery.db.fields.DurationField(*args, **kwargs)Bases: django_sorcery.db.fields.Field

Django like duration field.

form_classalias of django.forms.fields.DurationField

type_classalias of sqlalchemy.sql.sqltypes.Interval

class django_sorcery.db.fields.EmailField(*args, **kwargs)Bases: django_sorcery.db.fields.CharField

Django like email field.

default_validators = [<django.core.validators.EmailValidator object>]

form_classalias of django.forms.fields.EmailField

class django_sorcery.db.fields.EnumField(*args, **kwargs)Bases: django_sorcery.db.fields.Field

Django like choice field that uses an enum sqlalchemy type.

get_form_class(kwargs)Returns form field class.

get_type(type_class, type_kwargs)Returns sqlalchemy column type instance for the field.

get_type_kwargs(type_class, kwargs)Returns sqlalchemy type kwargs.

type_classalias of sqlalchemy.sql.sqltypes.Enum

class django_sorcery.db.fields.Field(*args, **kwargs)Bases: sqlalchemy.sql.schema.Column

38 Chapter 2. Quick Start

Page 43: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

Base django-esque field.

default_validators = []

form_class = None

get_column_kwargs(kwargs)Returns sqlalchemy column kwargs.

get_form_class(kwargs)Returns form field class.

get_type(type_class, type_kwargs)Returns sqlalchemy column type instance for the field.

get_type_class(kwargs)Returns sqlalchemy column type.

get_type_kwargs(type_class, kwargs)Returns sqlalchemy type kwargs.

get_validators(validators)Returns django validators for the field.

type_class = None

widget_class = None

class django_sorcery.db.fields.FloatField(*args, **kwargs)Bases: django_sorcery.db.fields.Field

Django like float field.

form_classalias of django.forms.fields.FloatField

get_type_kwargs(type_class, kwargs)Returns sqlalchemy type kwargs.

type_classalias of sqlalchemy.sql.sqltypes.Float

class django_sorcery.db.fields.IntegerField(*args, **kwargs)Bases: django_sorcery.db.fields.ValidateIntegerFieldMixin, django_sorcery.db.fields.Field

Django like integer field.

default_validators = [<function validate_integer>]

form_classalias of django.forms.fields.IntegerField

type_classalias of sqlalchemy.sql.sqltypes.Integer

class django_sorcery.db.fields.NullBooleanField(*args, **kwargs)Bases: django_sorcery.db.fields.BooleanField

Django like nullable boolean field.

form_classalias of django.forms.fields.NullBooleanField

get_column_kwargs(kwargs)Returns sqlalchemy column kwargs.

2.2. API Documentation 39

Page 44: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

class django_sorcery.db.fields.SlugField(*args, **kwargs)Bases: django_sorcery.db.fields.CharField

Django like slug field.

default_validators = [<django.core.validators.RegexValidator object>]

form_classalias of django.forms.fields.SlugField

class django_sorcery.db.fields.SmallIntegerField(*args, **kwargs)Bases: django_sorcery.db.fields.ValidateIntegerFieldMixin, django_sorcery.db.fields.Field

Django like small integer field.

default_validators = [<function validate_integer>]

form_classalias of django.forms.fields.IntegerField

type_classalias of sqlalchemy.sql.sqltypes.SmallInteger

class django_sorcery.db.fields.TextField(*args, **kwargs)Bases: django_sorcery.db.fields.CharField

Django like text field.

form_classalias of django.forms.fields.CharField

length_is_required = False

type_classalias of sqlalchemy.sql.sqltypes.Text

widget_classalias of django.forms.widgets.Textarea

class django_sorcery.db.fields.TimeField(*args, **kwargs)Bases: django_sorcery.db.fields.Field

Django like time field.

form_classalias of django.forms.fields.TimeField

type_classalias of sqlalchemy.sql.sqltypes.Time

class django_sorcery.db.fields.TimestampField(*args, **kwargs)Bases: django_sorcery.db.fields.DateTimeField

Django like datetime field that uses timestamp sqlalchemy type.

type_classalias of sqlalchemy.sql.sqltypes.TIMESTAMP

class django_sorcery.db.fields.URLField(*args, **kwargs)Bases: django_sorcery.db.fields.CharField

Django like url field.

default_validators = [<django.core.validators.URLValidator object>]

40 Chapter 2. Quick Start

Page 45: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

form_classalias of django.forms.fields.URLField

django_sorcery.db.middleware module

Django middleware support for sqlalchemy.

class django_sorcery.db.middleware.BaseMiddleware(get_response=None)Bases: object

Base middleware implementation that supports unit of work per request for django.

logger = <Logger django_sorcery.db.middleware (WARNING)>

process_request(request)Hook for adding arbitrary logic to request processing.

process_response(request, response)Commits or rollbacks scoped sessions depending on status code then removes them.

return_response(request, response)Hook for adding arbitrary logic to response processing.

class django_sorcery.db.middleware.SQLAlchemyDBMiddleware(get_response=None)Bases: django_sorcery.db.middleware.BaseMiddleware

A base SQLAlchemy db middleware.

Used by SQLAlchemy to provide a default middleware for a single db, it will first try to flush and if successfull,proceed with commit. If there are any errors during flush, will issue a rollback.

commit(request, response)Commits current scoped session.

db = None

flush(request, response)Flushes current scoped session.

remove(request, response)Removes current scoped session.

rollback(request, response)Rolls back current scoped session.

class django_sorcery.db.middleware.SQLAlchemyMiddleware(get_response=None)Bases: django_sorcery.db.middleware.SQLAlchemyDBMiddleware

A sqlalchemy middleware that manages all the dbs configured and initialized.

it will first try to flush all the configured and initialized SQLAlchemy instances and if successfull, proceed withcommit. If there are any errors during flush, all transactions will be rolled back.

db = {}

django_sorcery.db.mixins module

Common mixins used in models.

2.2. API Documentation 41

Page 46: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

class django_sorcery.db.mixins.CleanMixinBases: object

Mixin for adding django-style full_clean validation to any object.

Base model in sqlalchemy.SQLAlchemy already uses this mixin applied.

For example:

class Address(db.Model):city = db.Column(db.String(20))state = db.Column(db.String(2))date = db.Column(db.Date())

validators = [ValidateTogetherModelFields(["city", "state"]),

]

def clean_date(self):if self.date > datetime.date.today():

raise ValidationError("Cant pick future date")

def clean(self):if self.date.year < 1776 and self.state == "NY":

raise ValidationError("NY state did not exist before 1776")

clean(**kwargs)Hook for adding custom model validations before model is flushed.

Should raise ValidationError if any errors are found.

clean_fields(exclude=None, **kwargs)Clean all fields on object.

clean_nested_fields(exclude=None, **kwargs)Clean all nested fields which includes composites.

clean_relation_fields(exclude, **kwargs)Clean all relation fields.

full_clean(exclude=None, **kwargs)Run model’s full clean chain.

This will run all of these in this order:

• will validate all columns by using clean_<column> methods

• will validate all nested objects (e.g. composites) with full_clean

• will run through all registered validators on validators attribute

• will run full model validation with self.clean()

• if recursive kwarg is provided, will recursively clean all relations. Useful when all models needto be explicitly cleaned without flushing to DB.

run_validators(**kwargs)Check all model validators registered on validators attribute.

django_sorcery.db.models module

sqlalchemy model related things.

42 Chapter 2. Quick Start

Page 47: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

class django_sorcery.db.models.BaseBases: django_sorcery.db.mixins.CleanMixin

Base model class for SQLAlchemy.

Can be overwritten by subclasses:

query_class = None

Automatically added by declarative base for easier querying:

query = None objects = None

as_dict()Return a dict of column attributes.

class django_sorcery.db.models.BaseMeta(classname, bases, dict_, **kw)Bases: sqlalchemy.orm.decl_api.DeclarativeMeta

Base metaclass for models which registers models to DB model registry when models are created.

django_sorcery.db.models.autocoerce(cls)This function automatically registers attribute events that coerces types for the attribute using django’s formfields for a given model classs. If no class is provided, it will wire up coersion for all mappers so it can be usedas a class decorator or globally.

@autocoerce_propertiesclass MyModel(db.Model):

...

or:

class MyModel(db.Model):...

autocoerce_properties()

Since django form fields are used for coersion, localization settings such as USE_THOUSAND_SEPARATOR,DATE_INPUT_FORMATS and DATETIME_INPUT_FORMATS control type conversions.

django_sorcery.db.models.autocoerce_properties(*attrs)This function automatically registers attribute events that coerces types for given attributes using django’s formfields.

::

class MyModel(db.Model): field1 = Column(. . . ) field2 = Column(. . . ) field3 = Column(. . . ) . . .

autocoerce_properties(MyModel.field1, MyModel.field2) # Will only force autocoersion on field1 andfield2

django_sorcery.db.models.clone(instance, *rels, **kwargs)

instance: Model a model instance

relations: list or relations or a tuple of relation and kwargs for that relation relationships to be clonedwith relationship and optionally kwargs

kwargs: dict string of any attribute values to be overridden

django_sorcery.db.models.deserialize(model, data)

model: a model class

data: dict values

2.2. API Documentation 43

Page 48: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

django_sorcery.db.models.full_clean_flush_handler(session, **kwargs)Signal handler for executing full_clean on all dirty and new objects in session.

django_sorcery.db.models.instant_defaults(cls)This function automatically registers attribute events that sets the column defaults to a model instance at modelinstance initialization provided that default values are simple types:

@instant_defaultsclass MyModel(db.Model):

attr = db.Column(..., default=1)

assert MyModel().default == 1

django_sorcery.db.models.serialize(instance, *rels)

instance: a model instance

rels: list of relations relationships to be serialized

django_sorcery.db.models.simple_repr(instance, fields=None)

instance: Model a model instance

fields: list list of fields to display on repr

django_sorcery.db.profiler module

sqlalchemy profiling things.

class django_sorcery.db.profiler.Query(timestamp, statement, parameters, duration)Bases: tuple

durationAlias for field number 3

parametersAlias for field number 2

statementAlias for field number 1

timestampAlias for field number 0

class django_sorcery.db.profiler.SQLAlchemyProfiler(exclude=None,record_queries=True)

Bases: object

A sqlalchemy profiler that hooks into sqlalchemy engine and pool events and generate stats.

Can also capture executed sql statements. Useful for profiling or testing sql statements.

clear()Clears collected stats.

countsReturns a dict of counts per sqlalchemy event operation like executed statements, commits, rollbacks, etc..

durationReturn total statement execution duration.

queriesReturns executed statements.

44 Chapter 2. Quick Start

Page 49: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

start()Starts profiling by wiring up sqlalchemy events.

statsReturns profiling stats.

stop()Stops profiling by detaching wired up sqlalchemy events.

class django_sorcery.db.profiler.SQLAlchemyProfilingMiddleware(get_response=None)Bases: object

Django middleware that provides sqlalchemy statistics.

header_resultsDetermines if stats should be returned as headers or not.

log(**kwargs)Log sqlalchemy stats for current request.

log_resultsDetermines if stats should be logged or not.

logger = <Logger django_sorcery.db.profiler (WARNING)>

process_request(request)Starts profiling and resets stats doe the request.

process_response(request, response)Logs current request stats and also returns stats as headers.

start()Starts profiling and disables restarts.

django_sorcery.db.query module

sqlalchemy query related things.

class django_sorcery.db.query.Operation(name, args, kwargs)Bases: tuple

argsAlias for field number 1

kwargsAlias for field number 2

nameAlias for field number 0

class django_sorcery.db.query.Query(entities, session=None)Bases: sqlalchemy.orm.query.Query

A customized sqlalchemy query.

filter(*args, **kwargs)Standard SQLAlchemy filtering plus django-like expressions can be provided:

For example:

2.2. API Documentation 45

Page 50: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

MyModel.objects.filter(MyModel.id == 5)MyModel.objects.filter(id=5)MyModel.objects.filter(id__gte=5)MyModel.objects.filter(relation__id__gte=5)

get(*args, **kwargs)Return an instance based on the given primary key identifier, either as args or kwargs for composite keys.

If no instance is found, returns None.

order_by(*criterion)Standard SQLAlchemy ordering plus django-like expressions can be provided:

For example:

MyModel.objects.order_by("-id")MyModel.objects.order_by("name")

class django_sorcery.db.query.QueryProperty(db, model=None, *args, **kwargs)Bases: object

A property class that returns a session scoped query object against the class when called. Used by theSQLAlchemy.queryproperty

For example:

>>> class MyView(object):... queryset = db.queryproperty(FooModel)

You can even pass default filtering criteria if needed:

>>> class MyView(object):... queryset = db.queryproperty(FooModel, to_be_deleted=False)

In addition this pattern can be used to implement Django’s ORM style model managers:

>>> class UserModel(db.Model):... id = db.Column(db.Integer(), primary_key=True)... username = db.Column(db.String())... is_active = db.Column(db.Boolean())...... active = db.queryproperty(is_active=True)

That can be used directly:

>>> UserModel.metadata.create_all(bind=db.engine)>>> db.add_all([... UserModel(id=1, username='foo', is_active=False),... UserModel(id=2, username='bar', is_active=True),... ])>>> db.flush()

>>> UserModel.objects.all()[UserModel(id=1, is_active=False, username='foo'), UserModel(id=2, is_active=True,→˓ username='bar')]>>> UserModel.active.all()[UserModel(id=2, is_active=True, username='bar')]

This pattern is very useful when combined with Django style views:

46 Chapter 2. Quick Start

Page 51: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

>>> class MyView(object):... queryset = UserModel.active

>>> MyView().queryset.all()[UserModel(id=2, is_active=True, username='bar')]

Additional filters/options can be applied as well:

>>> class MyView(object):... queryset = UserModel.active.filter(UserModel.username == 'test')

>>> MyView().queryset.all()[]

django_sorcery.db.relations module

sqlalchemy relationship related things.

class django_sorcery.db.relations.RelationsMixinBases: object

Mixin that provides django like shortcuts for relationships.

ManyToMany(remote_cls, table_name=None, **kwargs)Use an event to build many-to-many relationship on a model and auto generates an association table or ifa model is provided as secondary argument:

class ModelOne(db.Model):pk = db.Column(.., primary_key=True)m2s = db.ManyToMany("ModelTwo", backref="m1s", table_name='m1m2s', ...)

class ModelTwo(db.Model):pk = db.Column(.., primary_key=True)...

or with back_populates:

class ModelOne(db.Model):pk = db.Column(.., primary_key=True)m2s = db.ManyToMany("ModelTwo", back_populates="m1s", table_name='m1m2s',

→˓ ...)

class ModelTwo(db.Model):pk = db.Column(.., primary_key=True)m1s = db.ManyToMany("ModelOne", back_populates="m2s", table_name='m1m2s',

→˓ ...)

will create ModelOne.m2s and ModelTwo.m1s relationship thru a provided secondary argument. If nosecondary argument is provided, table_name is required as it will be used for the autogenerated associationtable.

In the case of back_populates you have to provide the same table_name argument on both many-to-manydeclarations

ManyToOne(remote_cls, **kwargs)Use an event to build many-to-one relationship on a model and auto generates foreign key relationship onthe remote table:

2.2. API Documentation 47

Page 52: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

class ModelOne(db.Model):pk = db.Column(.., primary_key=True)m2 = db.ManyToOne("ModelTwo", ...)

class ModelTwo(db.Model):pk = db.Column(.., primary_key=True)...

will create ModelOne.m2_pk automatically for the relationship

OneToMany(remote_cls, **kwargs)Use an event to build one-to-many relationship on a model and auto generates foreign key relationshipfrom the remote table:

class ModelOne(db.Model): pk = db.Column(.., primary_key=True) m2 =db.OneToMany(“ModelTwo”, . . . )

class ModelTwo(db.Model): pk = db.Column(.., primary_key=True) . . .

will create ModelTwo.m1_pk automatically for the relationship

OneToOne(remote_cls, **kwargs)Use an event to build one-to-many relationship on a model and auto generates foreign key relationshipfrom the remote table:

class ModelOne(db.Model): pk = db.Column(.., primary_key=True) m2 = db.OneToOne(“ModelTwo”,. . . )

class ModelTwo(db.Model): pk = db.Column(.., primary_key=True) . . .

will create ModelTwo.m1_pk automatically for the relationship

django_sorcery.db.relations.declare_first_relationships_handler(cls)Declare first signal handler which connects relationships on the class.

Can be called multiple times so once relationships are set, they are removed from model

django_sorcery.db.session module

sqlalchemy session related things.

class django_sorcery.db.session.SignallingSession(*args, **kwargs)Bases: sqlalchemy.orm.session.Session

A custom sqlalchemy session implementation that provides signals.

query(*args, **kwargs)Override to try to use the model.query_class.

django_sorcery.db.session.after_commit(session)

django_sorcery.db.session.after_flush(session, flush_context)

django_sorcery.db.session.after_rollback(session)

django_sorcery.db.session.before_commit(session)

django_sorcery.db.session.before_flush(session, flush_context, instances)

django_sorcery.db.session.record_models(session, flush_context=None, instances=None)

48 Chapter 2. Quick Start

Page 53: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

django_sorcery.db.signals module

Signals

Implements some basic signals using blinker

class django_sorcery.db.signals.NamespaceBases: blinker.base.Namespace

A signal namespace that also manages scoped signals.

scoped_signalsReturns all scoped signals.

scopedsignal(name, doc=None)Returns the scoped signal for a given name.

class django_sorcery.db.signals.ScopedSignal(name, doc=None)Bases: blinker.base.NamedSignal

Same as NamedSignal but signal is scoped to a thread.

In other words, if a receiver is attached within a specific thread, even if signal is sent in another thread, inthat other thread no receivers will be present and hence nothing will execute. Useful for adding one-off signalhandlers for example to be executed at the end of unit-of-work (e.g. request) without adding a possibility thatanother thread might start executing the receiver.

cleanup()Cleans up signal for the current thread scope.

receiversReturn all thread scoped receivers.

django_sorcery.db.sqlalchemy module

SQLAlchemy goodies that provides a nice interface to using sqlalchemy with django.

class django_sorcery.db.sqlalchemy.SQLAlchemy(url, **kwargs)Bases: django_sorcery.db.relations.RelationsMixin

This class itself is a scoped session and provides very thin and useful abstractions and conventions for usingsqlalchemy with django.

class BaseComposite(*args, **kwargs)Bases: object

Base class for creating composite classes which CompositeField will understand.

For example:

class MyComposite(object):foo = db.Column(db.Integer())bar = db.Column(db.Integer())

class MyModel(db.Model):test = db.CompositeField(MyComposite)# both test_foo and test_bar columns will be added to model# their instrumented properties will be _test_foo and _test_bar

2.2. API Documentation 49

Page 54: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

as_dict()Serializer composite to a dictionary.

class CompositeField(class_, **kwargs)Bases: sqlalchemy.orm.descriptor_props.CompositeProperty

Composite field which understands composite objects with builtin columns.

See BaseComposite for examples.

instrument_class(mapper)Hook called by the Mapper to the property to initiate instrumentation of the class attribute managedby this MapperProperty.

The MapperProperty here will typically call out to the attributes module to set up an Instrumente-dAttribute.

This step is the first of two steps to set up an InstrumentedAttribute, and is called early in the mappersetup process.

The second step is typically the init_class_attribute step, called from StrategizedProperty via thepost_instrument_class() hook. This step assigns additional state to the InstrumentedAttribute(specifically the “impl”) which has been determined after the MapperProperty has determined whatkind of persistence management it needs to do (e.g. scalar, object, collection, etc).

Table(name, *args, **kwargs)Returns a sqlalchemy table that is automatically added to metadata.

add(*args, **kwargs)

add_all(*args, **kwargs)

args(*args, **kwargs)Useful for setting table args and mapper args on models.

atomic(savepoint=True)Create a savepoint or transaction scope.

autocommit

autoflush

begin(*args, **kwargs)

begin_nested(*args, **kwargs)

bind

bind_mapper(*args, **kwargs)

bind_table(*args, **kwargs)

bulk_insert_mappings(*args, **kwargs)

bulk_save_objects(*args, **kwargs)

bulk_update_mappings(*args, **kwargs)

close(*args, **kwargs)

close_all(*args, **kwargs)

commit(*args, **kwargs)

connection(*args, **kwargs)

connection_callable

50 Chapter 2. Quick Start

Page 55: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

create_all()Create the schema in db.

delete(*args, **kwargs)

deleted

dirty

dispatch

drop_all()Drop the schema in db.

enable_baked_queries

enable_relationship_loading(*args, **kwargs)

engineCurrent engine.

execute(*args, **kwargs)

expire(*args, **kwargs)

expire_all(*args, **kwargs)

expire_on_commit

expunge(*args, **kwargs)

expunge_all(*args, **kwargs)

flush(*args, **kwargs)

future

get(*args, **kwargs)

get_bind(*args, **kwargs)

get_nested_transaction(*args, **kwargs)

get_transaction(*args, **kwargs)

hash_key

identity_key(*args, **kwargs)

identity_map

in_nested_transaction(*args, **kwargs)

in_transaction(*args, **kwargs)

info

inspectorReturns engine inspector.

Useful for querying for db schema info.

invalidate(*args, **kwargs)

is_active

is_modified(*args, **kwargs)

make_middleware()Creates a middleware to be used in a django application.

2.2. API Documentation 51

Page 56: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

merge(*args, **kwargs)

metadata_classalias of sqlalchemy.sql.schema.MetaData

model_classalias of django_sorcery.db.models.Base

new

no_autoflush

object_session(*args, **kwargs)

prepare(*args, **kwargs)

query(*args, **kwargs)

query_classalias of django_sorcery.db.query.Query

queryproperty(*args, **kwargs)Generate a query property for a model.

refresh(*args, **kwargs)

registryReturns scoped registry instance.

registry_classalias of sqlalchemy.util._collections.ThreadLocalRegistry

remove()Remove the current scoped session.

rollback(*args, **kwargs)

scalar(*args, **kwargs)

scalars(*args, **kwargs)

session(**kwargs)Return the current session, creating it if necessary using session_factory for the current scope Any kwargsprovided will be passed on to the session_factory.

If there’s already a session in current scope, will raise InvalidRequestError

session_classalias of django_sorcery.db.session.SignallingSession

session_factoryCurrent session factory to create sessions.

transaction

twophase

django_sorcery.db.sqlalchemy.instrument(name)

django_sorcery.db.sqlalchemy.makeprop(name)

django_sorcery.db.transaction module

sqlalchemy transaction related things.

52 Chapter 2. Quick Start

Page 57: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

class django_sorcery.db.transaction.TransactionContext(*dbs, **kwargs)Bases: object

Transaction context manager for maintaining a transaction or savepoint.

django_sorcery.db.url module

django_sorcery.db.url.boolean(x)

django_sorcery.db.url.get_settings(alias)Returns database settings from either SQLALCHEMY_CONNECTIONS setting or DATABASES setting.

django_sorcery.db.url.importable(x)

django_sorcery.db.url.importable_list(x)

django_sorcery.db.url.importable_list_tuples(x)

django_sorcery.db.url.integer(x)

django_sorcery.db.url.make_url(alias_or_url)

alias_or_url: str name of the alias or url as string

django_sorcery.db.url.make_url_from_settings(alias)

alias: str name of the alias

Overall settings are very similar with django database settings with a few extra keys.

USER - database user

PASSWORD - database user password

HOST - database host

NAME - database name

PORT - database name

DIALECT - dialect to be used in url, if not provided, will use the DIALECT_MAP to figure out a dialect to beused in sqlalchemy url

DRIVER - If provided, will be used as the driver in sqlalchemy url

SQLALCHEMY - If provided, a custom sqlalchemy.SQLAlchemy class to be used

QUERY - querystring arguments for sqlalchemy url

ALCHEMY_OPTIONS - Optional arguments to be used to initialize the sqlalchemy.SQLAlchemy instance

• session_class - a custom session class to be used

• registry_class - a custom registy class to be used for scoping

• model_class - a custom base model class to be used for declarative base models.

• metadata_class - a custom metadata class used in delclarative models.

• metadata_options - custom options to use in metadata creation such as specifying naming conven-tions.

• engine_options - arguments for sqlalchemy create_engine

• session_options - arguments for sqlalchemy sessionmaker

Other options are ignored.

2.2. API Documentation 53

Page 58: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

django_sorcery.db.url.string(x)

django_sorcery.db.url.string_list(x)

django_sorcery.db.utils module

class django_sorcery.db.utils.dbdictBases: dict

Holds all configured sqlalchemy.SQLAlchemy instances.

atomic(savepoint=True)Returns a context manager/decorator that guarantee atomic execution of a given block or function acrossall configured and initialized SQLAlchemy instances.

commit()Applies commit on all registered databases.

flush()Applies flush on all registered databases.

get(alias=None, cls=<class ’django_sorcery.db.sqlalchemy.SQLAlchemy’>, **kwargs)Returns a sqlalchemy.SQLAlchemy instance from configuration and registers it.

Can return a custom sqlalchemy.SQLAlchemy instance thru args or thru SQLALCHEMY databasesetting in configuration.

remove()Applies remove on all registered databases.

rollback()Applies rollback on all registered databases.

update([E ], **F)→ None. Update D from dict/iterable E and F.If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a.keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] =F[k]

django_sorcery.db.utils.index_foreign_keys(*args)Generates indexes for all foreign keys for a table or metadata tables.

django_sorcery.formsets package

Submodules

django_sorcery.formsets.base module

Helper functions for creating FormSet classes from SQLAlchemy models.

class django_sorcery.formsets.base.BaseModelFormSet(data=None, files=None,auto_id=’id_%s’, prefix=None,queryset=None, initial=None,**kwargs)

Bases: django.forms.formsets.BaseFormSet

A FormSet for editing a queryset and/or adding new objects to it.

absolute_max = 2000

54 Chapter 2. Quick Start

Page 59: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

add_fields(form, index)A hook for adding extra fields on to each form instance.

delete_existing(obj, **kwargs)Deletes an existing model instance.

get_queryset()Returns a query for the model.

initial_form_count()Return the number of forms that are required in this FormSet.

model = None

save(flush=True, **kwargs)Save model instances for every form, adding and changing instances as necessary, and return the list ofinstances.

session = None

unique_fields = {}

django_sorcery.formsets.base.modelformset_factory(model, form=<class’django_sorcery.forms.ModelForm’>,formfield_callback=None,formset=<class’django_sorcery.formsets.base.BaseModelFormSet’>,extra=1, can_delete=False,can_order=False, max_num=None,fields=None, exclude=None, wid-gets=None, validate_max=False,localized_fields=None, la-bels=None, help_texts=None,error_messages=None,min_num=None, val-idate_min=False,field_classes=None, ses-sion=None)

Return a FormSet class for the given sqlalchemy model class.

django_sorcery.formsets.inline module

InlineFormSet for sqlalchemy.

class django_sorcery.formsets.inline.BaseInlineFormSet(data=None, files=None,instance=None,save_as_new=False, pre-fix=None, queryset=None,**kwargs)

Bases: django_sorcery.formsets.base.BaseModelFormSet

A formset for child objects related to a parent.

classmethod get_default_prefix()

initial_form_count()Return the number of forms that are required in this FormSet.

2.2. API Documentation 55

Page 60: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

save(flush=False, **kwargs)Save model instances for every form, adding and changing instances as necessary, and return the list ofinstances.

django_sorcery.formsets.inline.inlineformset_factory(parent_model=None,model=None, rela-tion=None, form=<class’django_sorcery.forms.ModelForm’>,formset=<class’django_sorcery.formsets.inline.BaseInlineFormSet’>,fk_name=None, fields=None,exclude=None, ex-tra=3, can_order=False,can_delete=True,max_num=None, form-field_callback=None,widgets=None, vali-date_max=False, local-ized_fields=None, la-bels=None, help_texts=None,error_messages=None,min_num=None, val-idate_min=False,field_classes=None, ses-sion=None)

Return an InlineFormSet for the given kwargs.

fk_name must be provided if model has more than one ForeignKey to parent_model.

django_sorcery.management package

Subpackages

django_sorcery.management.commands package

Submodules

django_sorcery.management.commands.sorcery module

Sorcery command namespace.

class django_sorcery.management.commands.sorcery.Command(stdout=None,stderr=None,no_color=False,force_color=False)

Bases: django_sorcery.management.base.NamespacedCommand

Namespaced commands for sorcery.

class MetaBases: object

namespace = 'sorcery'

createallalias of django_sorcery.management.commands.sorcery_createall.CreateAll

56 Chapter 2. Quick Start

Page 61: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

currentalias of django_sorcery.management.commands.sorcery_current.Current

downgradealias of django_sorcery.management.commands.sorcery_downgrade.Downgrade

dropallalias of django_sorcery.management.commands.sorcery_dropall.DropAll

headsalias of django_sorcery.management.commands.sorcery_heads.ShowHeads

help = 'django-sorcery management commands'

historyalias of django_sorcery.management.commands.sorcery_history.History

revisionalias of django_sorcery.management.commands.sorcery_revision.Revision

stampalias of django_sorcery.management.commands.sorcery_stamp.Stamp

upgradealias of django_sorcery.management.commands.sorcery_upgrade.Upgrade

django_sorcery.management.commands.sorcery_createall module

CreateAll command.

django_sorcery.management.commands.sorcery_createall.Commandalias of django_sorcery.management.commands.sorcery_createall.CreateAll

class django_sorcery.management.commands.sorcery_createall.CreateAll(stdout=None,stderr=None,no_color=False,force_color=False)

Bases: django.core.management.base.BaseCommand

Creates db schema using metadata.create_all.

add_arguments(parser)Entry point for subclassed commands to add custom arguments.

handle(*args, **kwargs)The actual logic of the command. Subclasses must implement this method.

help = 'Creates SQLAlchemy database schemas'

django_sorcery.management.commands.sorcery_current module

Current command.

django_sorcery.management.commands.sorcery_current.Commandalias of django_sorcery.management.commands.sorcery_current.Current

2.2. API Documentation 57

Page 62: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

class django_sorcery.management.commands.sorcery_current.Current(stdout=None,stderr=None,no_color=False,force_color=False)

Bases: django_sorcery.management.alembic.AlembicCommand

Shows current db revisions.

add_arguments(parser)Entry point for subclassed commands to add custom arguments.

display_version(rev, context, verbose=False, appconfig=None)Displays the alembic revision.

handle(app_label=None, verbosity=0, **kwargs)The actual logic of the command. Subclasses must implement this method.

help = 'Show current db revisions'

django_sorcery.management.commands.sorcery_downgrade module

Downgrade command.

django_sorcery.management.commands.sorcery_downgrade.Commandalias of django_sorcery.management.commands.sorcery_downgrade.Downgrade

class django_sorcery.management.commands.sorcery_downgrade.Downgrade(stdout=None,stderr=None,no_color=False,force_color=False)

Bases: django_sorcery.management.alembic.AlembicCommand

Apply downgrade migration revisions.

add_arguments(parser)Entry point for subclassed commands to add custom arguments.

downgrade(rev, context, appconfig, revision)Executes alembic downgrade revisions to the given revision.

handle(app_label=None, revision=None, sql=False, **kwargs)The actual logic of the command. Subclasses must implement this method.

help = 'Apply migration revisions'

django_sorcery.management.commands.sorcery_dropall module

DropAll command.

django_sorcery.management.commands.sorcery_dropall.Commandalias of django_sorcery.management.commands.sorcery_dropall.DropAll

class django_sorcery.management.commands.sorcery_dropall.DropAll(stdout=None,stderr=None,no_color=False,force_color=False)

Bases: django.core.management.base.BaseCommand

Drops database schemas using metadata.drop_all.

58 Chapter 2. Quick Start

Page 63: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

add_arguments(parser)Entry point for subclassed commands to add custom arguments.

handle(*args, **kwargs)The actual logic of the command. Subclasses must implement this method.

help = 'Drops SQLAlchemy database schemas'

django_sorcery.management.commands.sorcery_heads module

Heads command.

django_sorcery.management.commands.sorcery_heads.Commandalias of django_sorcery.management.commands.sorcery_heads.ShowHeads

class django_sorcery.management.commands.sorcery_heads.ShowHeads(stdout=None,stderr=None,no_color=False,force_color=False)

Bases: django_sorcery.management.alembic.AlembicCommand

Display alembic revision heads.

add_arguments(parser)Entry point for subclassed commands to add custom arguments.

handle(app_label=None, verbosity=0, **kwargs)The actual logic of the command. Subclasses must implement this method.

help = 'Display revision heads'

django_sorcery.management.commands.sorcery_history module

History command.

django_sorcery.management.commands.sorcery_history.Commandalias of django_sorcery.management.commands.sorcery_history.History

class django_sorcery.management.commands.sorcery_history.History(stdout=None,stderr=None,no_color=False,force_color=False)

Bases: django_sorcery.management.alembic.AlembicCommand

Display alembic revisions.

add_arguments(parser)Entry point for subclassed commands to add custom arguments.

handle(app_label=None, rev_range=None, verbosity=0, **kwargs)The actual logic of the command. Subclasses must implement this method.

help = 'Display alembic revisions'

print_history(appconfigs, verbose, base, head)Prints alembic revision history.

2.2. API Documentation 59

Page 64: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

django_sorcery.management.commands.sorcery_revision module

Revision command.

django_sorcery.management.commands.sorcery_revision.Commandalias of django_sorcery.management.commands.sorcery_revision.Revision

class django_sorcery.management.commands.sorcery_revision.Revision(stdout=None,stderr=None,no_color=False,force_color=False)

Bases: django_sorcery.management.alembic.AlembicCommand

Creates an alembic migration revision.

add_arguments(parser)Entry point for subclassed commands to add custom arguments.

generate_migration(rev, context, appconfig=None)Generate alembic migration.

handle(app_label, message=None, head=None, splice=None, branch_label=None, de-pends_on=None, rev_id=None, autogenerate=None, **kwargs)

The actual logic of the command. Subclasses must implement this method.

help = 'Create a migration revision'

django_sorcery.management.commands.sorcery_stamp module

Stamp command.

django_sorcery.management.commands.sorcery_stamp.Commandalias of django_sorcery.management.commands.sorcery_stamp.Stamp

class django_sorcery.management.commands.sorcery_stamp.Stamp(stdout=None,stderr=None,no_color=False,force_color=False)

Bases: django_sorcery.management.alembic.AlembicCommand

Stamp the revision table with migration revisions, doesn’t run any migrations.

add_arguments(parser)Entry point for subclassed commands to add custom arguments.

handle(app_label=None, revision=None, **kwargs)The actual logic of the command. Subclasses must implement this method.

help = "Stamp the revision table with migration revisions, doesn't run any migrations"

stamp(rev, context, appconfig, revision)Stamp the alembic revision.

django_sorcery.management.commands.sorcery_upgrade module

Upgrade command.

django_sorcery.management.commands.sorcery_upgrade.Commandalias of django_sorcery.management.commands.sorcery_upgrade.Upgrade

60 Chapter 2. Quick Start

Page 65: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

class django_sorcery.management.commands.sorcery_upgrade.Upgrade(stdout=None,stderr=None,no_color=False,force_color=False)

Bases: django_sorcery.management.alembic.AlembicCommand

Apply upgrade migration revisions.

add_arguments(parser)Entry point for subclassed commands to add custom arguments.

handle(app_label=None, revision=None, sql=False, **kwargs)The actual logic of the command. Subclasses must implement this method.

help = 'Apply migration revisions'

upgrade(rev, context, appconfig, revision)Executes alembic upgrade revisions to the given revision.

Submodules

django_sorcery.management.alembic module

Alembic Django command things.

class django_sorcery.management.alembic.AlembicAppConfig(name, config, script, db,app, version_path, ta-bles)

Bases: tuple

appAlias for field number 4

configAlias for field number 1

dbAlias for field number 3

nameAlias for field number 0

scriptAlias for field number 2

tablesAlias for field number 6

version_pathAlias for field number 5

class django_sorcery.management.alembic.AlembicCommand(stdout=None, stderr=None,no_color=False,force_color=False)

Bases: django.core.management.base.BaseCommand

Base alembic django command.

get_app_config(app, db)Return alembic config for an app.

2.2. API Documentation 61

Page 66: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

get_app_version_path(app)Returns the default migration directory location of al app.

get_common_config(context)Common alembic configuration.

get_config_script(config)Returns the alembic script directory for the config.

lookup_app(app_label)Looks up an app’s alembic config.

run_env(context, appconfig)Executes an alembic context, just like the env.py file of alembic.

run_migrations_offline(context, appconfig)Executes an offline alembic context.

run_migrations_online(context, appconfig)Executes an online alembic context.

sorcery_appsAll sorcery apps and their alembic configs.

django_sorcery.management.base module

Namespaced Django command.

class django_sorcery.management.base.NamespacedCommand(stdout=None, stderr=None,no_color=False,force_color=False)

Bases: django.core.management.base.BaseCommand

Namespaced django command implementation.

commandsReturns the subcommands in the namespace.

create_parser(prog_name, subcommand)Create and return the ArgumentParser which will be used to parse the arguments to this command.

print_help(prog_name, subcommand)Print the help message for this command, derived from self.usage().

run_command_from_argv(command, argv)Runs the subcommand with namespace adjusted argv.

run_from_argv(argv)Set up any environment changes requested (e.g., Python path and Django settings), then run this com-mand. If the command raises a CommandError, intercept it and print it sensibly to stderr. If the--traceback option is present or the raised Exception is not CommandError, raise it.

django_sorcery.validators package

Submodules

django_sorcery.validators.base module

Validators.

62 Chapter 2. Quick Start

Page 67: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

class django_sorcery.validators.base.ValidateCantRemove(field, message=None,code=None)

Bases: object

Validate that for data cannot be removed for given field.

For example:

class MyModel(db.Model):foo = db.Column(db.String())

validators = [ValidateCantRemove('foo'),

]

code = 'remove'

message = 'Cannot remove existing data.'

class django_sorcery.validators.base.ValidateEmptyWhen(field, predicate, mes-sage=None, code=None)

Bases: object

Validator for checking a field is empty when predicate is True.

Useful to conditionally enforce a field is not provided depending on related field

For example:

class MyModel(db.Model):foo = db.Column(db.String())bar = db.Column(db.String())

validators = [# do not allow to set bar unless foo is presentValidateEmptyWhen('bar', lambda m: not m.foo),

]

allow_empty = True

code = 'empty'

message = 'Cannot provide a value to this field.'

class django_sorcery.validators.base.ValidateNotEmptyWhen(field, predicate,message=None,code=None)

Bases: django_sorcery.validators.base.ValidateEmptyWhen

Validator for checking a field is provided when predicate is True.

Useful to conditionally enforce a field is provided depending on related field

For example:

class MyModel(db.Model):foo = db.Column(db.String())bar = db.Column(db.String())

validators = [# enforce bar is provided when foo is providedValidateNotEmptyWhen('bar', lambda m: m.foo),

]

2.2. API Documentation 63

Page 68: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

allow_empty = False

code = 'not_empty'

message = 'This field is required.'

class django_sorcery.validators.base.ValidateOnlyOneOf(fields, required=True, mes-sage=None, code=None)

Bases: object

Validate that only one of given fields is provided.

For example:

class MyModel(db.Model):foo = db.Column(db.String())bar = db.Column(db.String())

validators = [# enforce only either foo or bar are providedValidateOnlyOneOf(['foo', 'bar']),

]

code = 'exclusive'

message = 'Only one of %(fields)s is allowed.'

class django_sorcery.validators.base.ValidateTogetherModelFields(fields, mes-sage=None,code=None)

Bases: object

Validator for checking that multiple model fields are always saved together.

For example:

class MyModel(db.Model):foo = db.Column(db.Integer())bar = db.Column(db.Integer())

validators = [ValidateTogetherModelFields(["foo", "bar"]),

]

code = 'required'

message = 'All %(fields)s are required.'

class django_sorcery.validators.base.ValidateUnique(session, *args, **kwargs)Bases: object

Validator for checking uniqueness of arbitrary list of attributes on a model.

For example:

class MyModel(db.Model):foo = db.Column(db.Integer())bar = db.Column(db.Integer())name = db.Column(db.Integer())

validators = [ValidateUnique(db, "name"), # checks for name uniqueness

(continues on next page)

64 Chapter 2. Quick Start

Page 69: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

(continued from previous page)

ValidateUnique(db, "foo", "bar"), # checks for foo and bar combination→˓uniqueness

]

code = 'required'

message = '%(fields)s must make a unique set.'

class django_sorcery.validators.base.ValidateValue(field, predicate, message=None,code=None)

Bases: object

Validator for checking correctness of a value by using a predicate callable.

Useful when other multiple fields need to be consulted to check if particular field is valid.

For example:

class MyModel(db.Model):foo = db.Column(db.String())bar = db.Column(db.String())

validators = [# allow only "bar" value when model.foo == "foo"ValidateValue('bar', lambda m: m.foo != 'foo' or b.bar == 'bar'),

]

code = 'invalid'

message = 'Please enter valid value.'

negated = False

django_sorcery.validators.runner module

Validation runner.

class django_sorcery.validators.runner.ValidationRunner(name=None, valida-tors=None, errors=None)

Bases: object

Helper class that can execute a bunch of validators on a given object.

is_valid(value, raise_exception=False)Runs all validators on given value and collect validation errors.

django_sorcery.views package

Submodules

django_sorcery.views.base module

Base model view things with sqlalchemy.

class django_sorcery.views.base.BaseMultipleObjectMixinBases: django_sorcery.views.base.SQLAlchemyMixin

Provides sqlalchemy support for list views.

2.2. API Documentation 65

Page 70: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

allow_empty = True

get_allow_empty()Return True if the view should display empty lists and False if a 404 should be raised instead.

get_ordering()Return the field or fields to use for ordering the queryset.

get_paginate_by(queryset)Get the number of items to paginate by, or None for no pagination.

get_paginate_orphans()Return the maximum number of orphans extend the last page by when paginating.

get_paginator(queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs)Return an instance of the paginator for this view.

get_queryset()Return the list of items for this view.

The return value must be an iterable and may be an instance of QuerySet in which case QuerySet specificbehavior will be enabled.

ordering = None

page_kwarg = 'page'

paginate_by = None

paginate_orphans = 0

paginate_queryset(queryset, page_size)Paginate queryset.

paginator_classalias of django.core.paginator.Paginator

class django_sorcery.views.base.BaseSingleObjectMixinBases: django_sorcery.views.base.SQLAlchemyMixin

Provides sqlalchemy support for detail views.

get_object(queryset=None)Return the object the view is displaying.

Require self.queryset and the primary key attributes or the slug attributes in the URLconf. Subclasses canoverride this to return any object

get_slug_field()Get the name of a slug field to be used to look up by slug.

object = None

query_pkg_and_slug = False

slug_field = 'slug'

slug_url_kwarg = 'slug'

class django_sorcery.views.base.SQLAlchemyMixinBases: django.views.generic.base.ContextMixin

Provides sqlalchemy model view support like query, model, session, etc..

context_object_name = None

66 Chapter 2. Quick Start

Page 71: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

classmethod get_model()Returns the model class.

get_model_template_name()Returns the base template path.

get_query_options()Returns sqlalchemy query options.

get_queryset()Return the QuerySet that will be used to look up the object.

This method is called by the default implementation of get_object() and may not be called if get_object()is overridden.

get_session()Returns the sqlalchemy session.

model = None

query_options = None

queryset = None

session = None

django_sorcery.views.detail module

Django detail view things for sqlalchemy.

class django_sorcery.views.detail.BaseDetailView(**kwargs)Bases: django_sorcery.views.detail.SingleObjectMixin, django.views.generic.base.View

A base view for displaying a single object.

get(request, *args, **kwargs)Handles GET on detail view.

class django_sorcery.views.detail.DetailView(**kwargs)Bases: django_sorcery.views.detail.SingleObjectTemplateResponseMixin,django_sorcery.views.detail.BaseDetailView

Render a “detail” view of an object.

By default this is a model instance looked up from self.queryset, but the view will support display of any objectby overriding self.get_object().

class django_sorcery.views.detail.SingleObjectMixinBases: django_sorcery.views.base.BaseSingleObjectMixin

Provide the ability to retrieve a single object for further manipulation.

get_context_data(**kwargs)Insert the single object into the context dict.

get_context_object_name(obj)Get the name to use for the object.

class django_sorcery.views.detail.SingleObjectTemplateResponseMixinBases: django.views.generic.base.TemplateResponseMixin

Provide the ability to retrieve template names.

2.2. API Documentation 67

Page 72: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

get_template_names()Returns template names for detail view.

template_name_field = None

template_name_suffix = '_detail'

django_sorcery.views.edit module

Django edit view things for sqlalchemy.

class django_sorcery.views.edit.BaseCreateView(**kwargs)Bases: django_sorcery.views.edit.ModelFormMixin, django_sorcery.views.edit.ProcessFormView

Base view for creating a new object instance.

Using this base class requires subclassing to provide a response mixin.

get(request, *args, **kwargs)Handle GET requests: instantiate a blank version of the form.

post(request, *args, **kwargs)Handle POST requests: instantiate a form instance with the passed POST variables and then check if it’svalid.

class django_sorcery.views.edit.BaseDeleteView(**kwargs)Bases: django_sorcery.views.edit.DeletionMixin, django_sorcery.views.detail.BaseDetailView

Base view for deleting an object.

Using this base class requires subclassing to provide a response mixin.

class django_sorcery.views.edit.BaseFormView(**kwargs)Bases: django.views.generic.edit.FormMixin, django_sorcery.views.edit.ProcessFormView

A base view for displaying a form.

class django_sorcery.views.edit.BaseUpdateView(**kwargs)Bases: django_sorcery.views.edit.ModelFormMixin, django_sorcery.views.edit.ProcessFormView

Base view for updating an existing object.

Using this base class requires subclassing to provide a response mixin.

get(request, *args, **kwargs)Handle GET requests: instantiate a blank version of the form.

post(request, *args, **kwargs)Handle POST requests: instantiate a form instance with the passed POST variables and then check if it’svalid.

class django_sorcery.views.edit.CreateView(**kwargs)Bases: django_sorcery.views.detail.SingleObjectTemplateResponseMixin,django_sorcery.views.edit.BaseCreateView

View for creating a new object, with a response rendered by a template.

template_name_suffix = '_form'

68 Chapter 2. Quick Start

Page 73: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

class django_sorcery.views.edit.DeleteView(**kwargs)Bases: django_sorcery.views.detail.SingleObjectTemplateResponseMixin,django_sorcery.views.edit.BaseDeleteView

View for deleting an object retrieved with self.get_object(), with a response rendered by a template.

template_name_suffix = '_confirm_delete'

class django_sorcery.views.edit.DeletionMixinBases: object

Provide the ability to delete objects.

delete(request, *args, **kwargs)Call the delete() method on the fetched object and then redirect to the success URL.

get_success_url()Returns the URL to redirect to after processing deletion.

post(request, *args, **kwargs)Handle POST request on deleve view.

success_url = None

class django_sorcery.views.edit.FormView(**kwargs)Bases: django.views.generic.base.TemplateResponseMixin, django_sorcery.views.edit.BaseFormView

A view for displaying a form and rendering a template response.

class django_sorcery.views.edit.ModelFormMixinBases: django.views.generic.edit.FormMixin, django_sorcery.views.detail.SingleObjectMixin

Provide a way to show and handle a ModelForm in a request.

fields = None

form_valid(form)If the form is valid, redirect to the supplied URL.

get_form_class()Return the form class to use.

get_form_kwargs()Return the keyword arguments for instantiating the form.

get_success_url()Return the URL to redirect to after processing a valid form.

class django_sorcery.views.edit.ProcessFormView(**kwargs)Bases: django.views.generic.base.View

Render a form on GET and processes it on POST.

get(request, *args, **kwargs)Handle GET requests: instantiate a blank version of the form.

post(request, *args, **kwargs)Handle POST requests: instantiate a form instance with the passed POST variables and then check if it’svalid.

put(request, *args, **kwargs)Handle POST requests: instantiate a form instance with the passed POST variables and then check if it’svalid.

2.2. API Documentation 69

Page 74: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

class django_sorcery.views.edit.UpdateView(**kwargs)Bases: django_sorcery.views.detail.SingleObjectTemplateResponseMixin,django_sorcery.views.edit.BaseUpdateView

View for updating an object, with a response rendered by a template.

template_name_suffix = '_form'

django_sorcery.views.list module

Django list view things for sqlalchemy.

class django_sorcery.views.list.BaseListView(**kwargs)Bases: django_sorcery.views.list.MultipleObjectMixin, django.views.generic.base.View

A base view for displaying a list of objects.

get(request, *args, **kwargs)Handle GET request on list view.

class django_sorcery.views.list.ListView(**kwargs)Bases: django_sorcery.views.list.MultipleObjectTemplateResponseMixin,django_sorcery.views.list.BaseListView

Render some list of objects, set by self.model or self.queryset.

self.queryset can actually be any iterable of items, not just a queryset.

class django_sorcery.views.list.MultipleObjectMixinBases: django_sorcery.views.base.BaseMultipleObjectMixin

A mixin for views manipulating multiple objects.

context_object_name = 'object_list'

get_context_data(object_list=None, **kwargs)Get the context for this view.

get_context_object_name(object_list)Get the name to use for the object.

class django_sorcery.views.list.MultipleObjectTemplateResponseMixinBases: django.views.generic.base.TemplateResponseMixin

Mixin for responding with a template and list of objects.

get_template_names()Return a list of template names to be used for the request.

Must return a list. May not be called if render_to_response is overridden.

template_name_suffix = '_list'

django_sorcery.viewsets package

class django_sorcery.viewsets.GenericViewSet(**kwargs)Bases: django.views.generic.base.TemplateResponseMixin, django.views.generic.base.View

Base class for all sqlalchemy model generic viewsets.

70 Chapter 2. Quick Start

Page 75: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

classmethod as_view(actions=None, **initkwargs)Main entry point for a request-response process.

classmethod get_extra_actions()Get the methods that are marked as an extra ViewSet @action.

get_template_names()Return a list of template names to be used for the request. Must return a list. May not be called ifrender_to_response() is overridden.

class django_sorcery.viewsets.ModelViewSet(**kwargs)Bases: django_sorcery.viewsets.mixins.CreateModelMixin, django_sorcery.viewsets.mixins.UpdateModelMixin, django_sorcery.viewsets.mixins.DeleteModelMixin, django_sorcery.viewsets.base.ReadOnlyModelViewSet

A viewset that provides default new(), create(), retrieve(), edit(), update()‘, confirm_destroy()), destroy() andlist() actions.

When used with router, it will map the following operations to actions on the viewset

Method Path Action Route NameGET / list <resource name>-listPOST / create <resource name>-listGET /new/ new <resource name>-newGET /<pk>/ retrieve <resource name>-detailPOST /<pk>/ update <resource name>-detailPUT /<pk>/ update <resource name>-detailPATCH /<pk>/ update <resource name>-detailDELETE /<pk>/ destroy <resource name>-detailGET /<pk>/edit/ edit <resource name>-editGET /<pk>/delete/ confirm_destoy <resource name>-deletePOST /<pk>/delete/ destroy <resource name>-delete

class django_sorcery.viewsets.ReadOnlyModelViewSet(**kwargs)Bases: django_sorcery.viewsets.mixins.ListModelMixin, django_sorcery.viewsets.mixins.RetrieveModelMixin, django_sorcery.viewsets.base.GenericViewSet

A viewset that provides default list() and retrieve() actions.

When used with router, it will map the following operations to actions on the viewset

Method Path Action Route NameGET / list <resource name>-listGET /<pk>/ retrieve <resource name>-detail

class django_sorcery.viewsets.CreateModelMixinBases: django_sorcery.viewsets.mixins.ModelFormMixin

A mixin for supporting creating objects.

When used with router, it will map the following operations to actions on the viewset

Method Path Action Route NamePOST / create <resource name>-listGET /new/ new <resource name>-new

2.2. API Documentation 71

Page 76: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

create(request, *args, **kwargs)Create action for creating an object.

get_create_context_data(**kwargs)Returns new context data for template rendering.

new(request, *args, **kwargs)New action for displaying a form for creating an object.

class django_sorcery.viewsets.DeleteModelMixinBases: django_sorcery.viewsets.mixins.RetrieveModelMixin

A mixin for supporting deleting objects.

When used with router, it will map the following operations to actions on the viewset

Method Path Action Route NameGET /<pk>/delete/ confirm_destoy <resource name>-deletePOST /<pk>/delete/ destroy <resource name>-deleteDELETE /<pk>/ destroy <resource name>-detail

confirm_destroy(request, *args, **kwargs)Confirm_destory action for displaying deletion confirmation for an object.

destroy(request, *args, **kwargs)Destroy action for deletion of an object.

destroy_success_url = None

get_destroy_context_data(**kwargs)Returns destory context data for rendering deletion confirmation page.

get_destroy_success_url()Return the url to redirect to after successful deletion of an object.

perform_destoy(obj)Performs the deletion operation.

class django_sorcery.viewsets.ListModelMixinBases: django_sorcery.views.base.BaseMultipleObjectMixin

A mixin for displaying a list of objects.

When used with router, it will map the following operations to actions on the viewset

Method Path Action Route NameGET / list <resource name>-list

get_list_context_data(**kwargs)Returns context data for list action.

get_list_context_object_name(object_list)Get the name to use for the object.

list(request, *args, **kwargs)List action for displaying a list of objects.

class django_sorcery.viewsets.ModelFormMixinBases: django.views.generic.edit.FormMixin, django_sorcery.viewsets.mixins.RetrieveModelMixin

72 Chapter 2. Quick Start

Page 77: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

Common mixin for handling sqlalchemy model forms in viewsets.

fields = None

form_class = None

form_invalid(form)Handles invalid form.

form_valid(form)Processes a valid form.

get_form_class()Returns the form class to be used.

get_form_context_data(**kwargs)Return form context data for template rendering.

get_form_kwargs()Returns the keyword arguments for instantiating the form.

get_success_url()Return the URL to redirect to after processing a valid form.

process_form(form)Checks if form is valid and processes accordingly.

success_url = None

class django_sorcery.viewsets.RetrieveModelMixinBases: django_sorcery.views.base.BaseSingleObjectMixin

A mixin for displaying a single object.

When used with router, it will map the following operations to actions on the viewset

Method Path Action Route NameGET /<pk>/ retrieve <resource name>-detail

get_detail_context_data(**kwargs)Returns detail context data for template rendering.

get_detail_context_object_name(obj)Get the name to use for the object.

get_url_kwargs(obj)

retrieve(request, *args, **kwargs)List action for displaying a single object.

class django_sorcery.viewsets.UpdateModelMixinBases: django_sorcery.viewsets.mixins.ModelFormMixin

A mixin for supporting updating objects.

When used with router, it will map the following operations to actions on the viewset

Method Path Action Route NameGET /<pk>/edit/ edit <resource name>-editPOST /<pk>/ update <resource name>-detailPUT /<pk>/ update <resource name>-detailPATCH /<pk>/ update <resource name>-detail

2.2. API Documentation 73

Page 78: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

edit(request, *args, **kwargs)Edit action for displaying a form for editing an object.

get_update_context_data(**kwargs)Returns edit context data for template rendering.

update(request, *args, **kwargs)Update action for updating an object.

Submodules

django_sorcery.viewsets.base module

Django REST Framework like model viewsets.

class django_sorcery.viewsets.base.GenericViewSet(**kwargs)Bases: django.views.generic.base.TemplateResponseMixin, django.views.generic.base.View

Base class for all sqlalchemy model generic viewsets.

classmethod as_view(actions=None, **initkwargs)Main entry point for a request-response process.

classmethod get_extra_actions()Get the methods that are marked as an extra ViewSet @action.

get_template_names()Return a list of template names to be used for the request. Must return a list. May not be called ifrender_to_response() is overridden.

class django_sorcery.viewsets.base.ModelViewSet(**kwargs)Bases: django_sorcery.viewsets.mixins.CreateModelMixin, django_sorcery.viewsets.mixins.UpdateModelMixin, django_sorcery.viewsets.mixins.DeleteModelMixin, django_sorcery.viewsets.base.ReadOnlyModelViewSet

A viewset that provides default new(), create(), retrieve(), edit(), update()‘, confirm_destroy()), destroy() andlist() actions.

When used with router, it will map the following operations to actions on the viewset

Method Path Action Route NameGET / list <resource name>-listPOST / create <resource name>-listGET /new/ new <resource name>-newGET /<pk>/ retrieve <resource name>-detailPOST /<pk>/ update <resource name>-detailPUT /<pk>/ update <resource name>-detailPATCH /<pk>/ update <resource name>-detailDELETE /<pk>/ destroy <resource name>-detailGET /<pk>/edit/ edit <resource name>-editGET /<pk>/delete/ confirm_destoy <resource name>-deletePOST /<pk>/delete/ destroy <resource name>-delete

class django_sorcery.viewsets.base.ReadOnlyModelViewSet(**kwargs)Bases: django_sorcery.viewsets.mixins.ListModelMixin, django_sorcery.

74 Chapter 2. Quick Start

Page 79: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

viewsets.mixins.RetrieveModelMixin, django_sorcery.viewsets.base.GenericViewSet

A viewset that provides default list() and retrieve() actions.

When used with router, it will map the following operations to actions on the viewset

Method Path Action Route NameGET / list <resource name>-listGET /<pk>/ retrieve <resource name>-detail

django_sorcery.viewsets.mixins module

Django REST Framework like viewset mixins for common model sqlalchemy actions.

class django_sorcery.viewsets.mixins.CreateModelMixinBases: django_sorcery.viewsets.mixins.ModelFormMixin

A mixin for supporting creating objects.

When used with router, it will map the following operations to actions on the viewset

Method Path Action Route NamePOST / create <resource name>-listGET /new/ new <resource name>-new

create(request, *args, **kwargs)Create action for creating an object.

get_create_context_data(**kwargs)Returns new context data for template rendering.

new(request, *args, **kwargs)New action for displaying a form for creating an object.

class django_sorcery.viewsets.mixins.DeleteModelMixinBases: django_sorcery.viewsets.mixins.RetrieveModelMixin

A mixin for supporting deleting objects.

When used with router, it will map the following operations to actions on the viewset

Method Path Action Route NameGET /<pk>/delete/ confirm_destoy <resource name>-deletePOST /<pk>/delete/ destroy <resource name>-deleteDELETE /<pk>/ destroy <resource name>-detail

confirm_destroy(request, *args, **kwargs)Confirm_destory action for displaying deletion confirmation for an object.

destroy(request, *args, **kwargs)Destroy action for deletion of an object.

destroy_success_url = None

get_destroy_context_data(**kwargs)Returns destory context data for rendering deletion confirmation page.

2.2. API Documentation 75

Page 80: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

get_destroy_success_url()Return the url to redirect to after successful deletion of an object.

perform_destoy(obj)Performs the deletion operation.

class django_sorcery.viewsets.mixins.ListModelMixinBases: django_sorcery.views.base.BaseMultipleObjectMixin

A mixin for displaying a list of objects.

When used with router, it will map the following operations to actions on the viewset

Method Path Action Route NameGET / list <resource name>-list

get_list_context_data(**kwargs)Returns context data for list action.

get_list_context_object_name(object_list)Get the name to use for the object.

list(request, *args, **kwargs)List action for displaying a list of objects.

class django_sorcery.viewsets.mixins.ModelFormMixinBases: django.views.generic.edit.FormMixin, django_sorcery.viewsets.mixins.RetrieveModelMixin

Common mixin for handling sqlalchemy model forms in viewsets.

fields = None

form_class = None

form_invalid(form)Handles invalid form.

form_valid(form)Processes a valid form.

get_form_class()Returns the form class to be used.

get_form_context_data(**kwargs)Return form context data for template rendering.

get_form_kwargs()Returns the keyword arguments for instantiating the form.

get_success_url()Return the URL to redirect to after processing a valid form.

process_form(form)Checks if form is valid and processes accordingly.

success_url = None

class django_sorcery.viewsets.mixins.RetrieveModelMixinBases: django_sorcery.views.base.BaseSingleObjectMixin

A mixin for displaying a single object.

When used with router, it will map the following operations to actions on the viewset

76 Chapter 2. Quick Start

Page 81: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

Method Path Action Route NameGET /<pk>/ retrieve <resource name>-detail

get_detail_context_data(**kwargs)Returns detail context data for template rendering.

get_detail_context_object_name(obj)Get the name to use for the object.

get_url_kwargs(obj)

retrieve(request, *args, **kwargs)List action for displaying a single object.

class django_sorcery.viewsets.mixins.UpdateModelMixinBases: django_sorcery.viewsets.mixins.ModelFormMixin

A mixin for supporting updating objects.

When used with router, it will map the following operations to actions on the viewset

Method Path Action Route NameGET /<pk>/edit/ edit <resource name>-editPOST /<pk>/ update <resource name>-detailPUT /<pk>/ update <resource name>-detailPATCH /<pk>/ update <resource name>-detail

edit(request, *args, **kwargs)Edit action for displaying a form for editing an object.

get_update_context_data(**kwargs)Returns edit context data for template rendering.

update(request, *args, **kwargs)Update action for updating an object.

Submodules

django_sorcery.exceptions module

Exceptions.

exception django_sorcery.exceptions.NestedValidationError(message, code=None,params=None)

Bases: django.core.exceptions.ValidationError

Django Validation error except which allows nested errors.

Useful for validating composite objects.

For example:

raise NestedValidationError({"field": ["error"],"composite": {

"field": ["error"],}

})

2.2. API Documentation 77

Page 82: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

update_error_dict(error_dict)

django_sorcery.fields module

Field mapping from SQLAlchemy type’s to form fields.

class django_sorcery.fields.EnumField(enum_class=None, choices=None, **kwargs)Bases: django.forms.fields.ChoiceField

Form field for using an Enum as choices.

bound_data(data, initial)Return the value that should be shown for this field on render of a bound form, given the submitted POSTdata for the field and the initial data, if any.

For most fields, this will simply be data; FileFields need to handle it a bit differently.

empty_value = None

prepare_value(value)

to_python(value)Return a string.

valid_value(value)Check to see if the provided value is a valid choice.

class django_sorcery.fields.ModelChoiceField(model, session, empty_label=’———’, required=True, wid-get=None, label=None, initial=None,help_text=”, to_field_name=None,limit_choices_to=None, **kwargs)

Bases: django.forms.fields.ChoiceField

A ChoiceField whose choices are a sqlalchemy model relationship.

choices

default_error_messages = {'invalid_choice': 'Select a valid choice. That choice is not one of the available choices.'}

get_bound_field(form, field_name)Return a BoundField instance that will be used when accessing the form field in a template.

get_limit_choices_to()Returns limit_choices_to for this model.

If it is a callable, invoke it and return the result

get_object(value)Returns model instance.

iteratoralias of ModelChoiceIterator

label_from_instance(obj)Returns label from model instance.

prepare_instance_value(obj)Returns primary key from instance.

prepare_value(obj)

queryset

78 Chapter 2. Quick Start

Page 83: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

to_python(value)Return a string.

validate(value)Validate that the input is in self.choices.

class django_sorcery.fields.ModelChoiceIterator(field)Bases: object

Iterator for sqlalchemy query for model choice fields.

choice(obj)Returns choice item for django choice field.

class django_sorcery.fields.ModelMultipleChoiceField(*args, **kwargs)Bases: django_sorcery.fields.ModelChoiceField

A ChoiceField whose choices are a sqlalchemy model list relationship.

default_error_messages = {'invalid_choice': 'Select a valid choice. %(value)s is not one of the available choices.', 'list': 'Enter a list of values.'}

hidden_widgetalias of django.forms.widgets.MultipleHiddenInput

prepare_value(value)

to_python(value)Return a string.

widgetalias of django.forms.widgets.SelectMultiple

django_sorcery.forms module

Helper functions for creating Form classes from SQLAlchemy models.

class django_sorcery.forms.BaseModelForm(data=None, files=None, auto_id=’id_%s’, pre-fix=None, initial=None, error_class=<class’django.forms.utils.ErrorList’>, la-bel_suffix=None, empty_permitted=False,instance=None, use_required_attribute=None,renderer=None, session=None)

Bases: django.forms.models.BaseModelForm

Base ModelForm for sqlalchemy models.

is_valid(rollback=True)Return True if the form has no errors, or False otherwise.

Will also rollback the session transaction.

model_to_dict()Returns a dict containing the data in instance suitable for passing as forms initial keyword argu-ment.

save(flush=True, **kwargs)Makes form’s self.instance model persistent and flushes the session.

save_instance(instance=None, cleaned_data=None)Updates form’s instance with cleaned data.

update_attribute(instance, name, field, value)Provides hooks for updating form instance’s attribute for a field with value.

2.2. API Documentation 79

Page 84: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

class django_sorcery.forms.ModelForm(data=None, files=None, auto_id=’id_%s’, pre-fix=None, initial=None, error_class=<class’django.forms.utils.ErrorList’>, label_suffix=None,empty_permitted=False, instance=None,use_required_attribute=None, renderer=None, ses-sion=None)

Bases: django_sorcery.forms.BaseModelForm

ModelForm base class for sqlalchemy models.

base_fields = {}

declared_fields = {}

media

class django_sorcery.forms.ModelFormMetaclassBases: django.forms.forms.DeclarativeFieldsMetaclass

ModelForm metaclass for sqlalchemy models.

class django_sorcery.forms.SQLAModelFormOptions(options=None)Bases: django.forms.models.ModelFormOptions

Model form options for sqlalchemy.

django_sorcery.forms.apply_limit_choices_to_form_field(formfield)Apply limit_choices_to to the formfield’s query if needed.

django_sorcery.forms.fields_for_model(model, session, fields=None, exclude=None,widgets=None, formfield_callback=None, local-ized_fields=None, labels=None, help_texts=None,error_messages=None, field_classes=None, ap-ply_limit_choices_to=True, **kwargs)

Returns a dictionary containing form fields for a given model.

django_sorcery.forms.model_to_dict(instance, fields=None, exclude=None)Return a dict containing the data in instance suitable for passing as a Form’s initial keyword argument.

fields is an optional list of field names. If provided, return only the named.

exclude is an optional list of field names. If provided, exclude the named from the returned dict, even if theyare listed in the fields argument.

django_sorcery.forms.modelform_factory(model, form=<class’django_sorcery.forms.ModelForm’>, form-field_callback=None, **kwargs)

Return a ModelForm class containing form fields for the given model.

django_sorcery.pytest_plugin module

pytest plugins.

django_sorcery.pytest_plugin.sqlalchemy_profiler()pytest fixture for sqlalchemy profiler.

django_sorcery.pytest_plugin.transact()pytest transact fixture for sqlalchemy.

80 Chapter 2. Quick Start

Page 85: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

django_sorcery.routers module

Django REST Framework like router for viewsets.

class django_sorcery.routers.BaseRouterBases: object

Base router.

get_default_base_name(viewset)If base_name is not specified, attempt to automatically determine it from the viewset.

get_urls()Return a list of URL patterns, given the registered viewsets.

register(prefix, viewset, base_name=None)Registers a viewset for route generation.

urlsURL’s routed.

class django_sorcery.routers.DynamicRoute(url, name, detail, initkwargs)Bases: tuple

detailAlias for field number 2

initkwargsAlias for field number 3

nameAlias for field number 1

urlAlias for field number 0

class django_sorcery.routers.Route(url, mapping, name, detail, initkwargs)Bases: tuple

detailAlias for field number 3

initkwargsAlias for field number 4

mappingAlias for field number 1

nameAlias for field number 2

urlAlias for field number 0

class django_sorcery.routers.SimpleRouter(trailing_slash=True)Bases: django_sorcery.routers.BaseRouter

Generates url patterns that map requests to a viewset’s action functions.

It will map the following operations to following actions on the viewset:

2.2. API Documentation 81

Page 86: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

Method Path Action Route NameGET /<resource>/ list <resource>-listPOST /<resource>/ create <resource>-listGET /<resource>/new/ new <resource>-newGET /<resource>/<pk>/ retrieve <resource>-detailPOST /<resource>/<pk>/ update <resource>-detailPUT /<resource>/<pk>/ update <resource>-detailPATCH /<resource>/<pk>/ update <resource>-detailDELETE /<resource>/<pk>/ destroy <resource>-detailGET /<resource>/<pk>/edit/ edit <resource>-editGET /<resource>/<pk>/delete/ confirm_destoy <resource>-deletePOST /<resource>/<pk>/delete/ destroy <resource>-delete

get_default_base_name(viewset)If base_name is not specified, attempt to automatically determine it from the viewset.

get_lookup_regex(viewset, lookup_prefix=”)Given a viewset, return the portion of URL regex that is used to match against a single instance.

Note that lookup_prefix is not used directly inside REST rest_framework itself, but is required in order tonicely support nested router implementations, such as drf-nested-routers.

https://github.com/alanjds/drf-nested-routers

get_method_map(viewset, method_map)Given a viewset, and a mapping of http methods to actions, return a new mapping which only includesany mappings that are actually implemented by the viewset.

get_routes(viewset)Augment self.routes with any dynamically generated routes.

Returns a list of the Route namedtuple.

get_urls()Use the registered viewsets to generate a list of URL patterns.

routes = [Route(url='^{prefix}{trailing_slash}$', mapping={'get': 'list', 'post': 'create'}, name='{basename}-list', detail=False, initkwargs={'suffix': 'List'}), Route(url='^{prefix}/new{trailing_slash}$', mapping={'get': 'new'}, name='{basename}-new', detail=False, initkwargs={'suffix': 'New'}), DynamicRoute(url='^{prefix}/{url_path}{trailing_slash}$', name='{basename}-{url_name}', detail=False, initkwargs={}), Route(url='^{prefix}/{lookup}{trailing_slash}$', mapping={'get': 'retrieve', 'post': 'update', 'put': 'update', 'patch': 'update', 'delete': 'destroy'}, name='{basename}-detail', detail=True, initkwargs={'suffix': 'Instance'}), Route(url='^{prefix}/{lookup}/edit{trailing_slash}$', mapping={'get': 'edit'}, name='{basename}-edit', detail=True, initkwargs={'suffix': 'Instance'}), Route(url='^{prefix}/{lookup}/delete{trailing_slash}$', mapping={'get': 'confirm_destroy', 'post': 'destroy'}, name='{basename}-destroy', detail=True, initkwargs={'suffix': 'Instance'}), DynamicRoute(url='^{prefix}/{lookup}/{url_path}{trailing_slash}$', name='{basename}-{url_name}', detail=True, initkwargs={})]

django_sorcery.routers.action(methods=None, detail=None, url_path=None, url_name=None,**kwargs)

Mark a ViewSet method as a routable action.

Set the detail boolean to determine if this action should apply to instance/detail requests or collection/list re-quests.

django_sorcery.routers.escape_curly_brackets(url_path)Double brackets in regex of url_path for escape string formatting.

django_sorcery.shortcuts module

Some Django like shortcuts that support sqlalchemy models.

django_sorcery.shortcuts.get_list_or_404(klass, *args, **kwargs)Use filter() to return a list of objects, or raise a Http404 exception if the count is 0.

klass may be a Model or Query object. All other passed arguments used in filter() and keyword arguments areused in filter_by().

82 Chapter 2. Quick Start

Page 87: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

django_sorcery.shortcuts.get_object_or_404(klass, *args, **kwargs)Use session.get() to return an object, or raise a Http404 exception if the object does not exist.

klass may be a Model, or Query object. All other passed arguments and keyword arguments are used in the get()query.

django_sorcery.testing module

Testing utilities.

exception django_sorcery.testing.CommitExceptionBases: BaseException

Raised when a commit happens during testing.

class django_sorcery.testing.TransactBases: object

Helper context manager for handling transactions during tests. Perfect for testing a single unit of work.

For testing sqlalchemy apps the common pattern is to usually, start a transaction or savepoint, run the tests andonce the test is done rollback. Additionally it also prevents commits to the database so that every test gets thesame database state.

end()Rolls back transaction and removes session.

hook()Hooks commit events to prevent commits.

start()Starts transaction management and hooks commit events.

stop()Stops transaction management, rolls back transactions and unhooks commit events.

unhook()Unhooks commit events.

django_sorcery.utils module

Some common utilities.

django_sorcery.utils.get_args(func)Returns the names of the positional arguments for composite model inspection.

django_sorcery.utils.lower(value)Convert value to lowercase if possible.

For example:

>>> print(lower('HELLO'))hello>>> print(lower(5))5

django_sorcery.utils.make_args(*args, **kwargs)Useful for setting table args and mapper args on models and other things.

2.2. API Documentation 83

Page 88: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

django_sorcery.utils.sanitize_separators(value)Sanitize a value according to the current decimal and thousand separator setting.

Used with form field input.

django_sorcery.utils.setdefaultattr(obj, name, value)setdefault for object attributes.

84 Chapter 2. Quick Start

Page 89: Django Sorcery Documentation

CHAPTER 3

Indices and tables

• genindex

• modindex

• search

85

Page 90: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

86 Chapter 3. Indices and tables

Page 91: Django Sorcery Documentation

Python Module Index

ddjango_sorcery, 26django_sorcery.db, 26django_sorcery.db.alembic, 29django_sorcery.db.alembic.base, 29django_sorcery.db.alembic.signals, 29django_sorcery.db.composites, 36django_sorcery.db.fields, 36django_sorcery.db.meta, 29django_sorcery.db.meta.base, 29django_sorcery.db.meta.column, 29django_sorcery.db.meta.composite, 33django_sorcery.db.meta.model, 33django_sorcery.db.meta.relations, 35django_sorcery.db.middleware, 41django_sorcery.db.mixins, 41django_sorcery.db.models, 42django_sorcery.db.profiler, 44django_sorcery.db.query, 45django_sorcery.db.relations, 47django_sorcery.db.session, 48django_sorcery.db.signals, 49django_sorcery.db.sqlalchemy, 49django_sorcery.db.transaction, 52django_sorcery.db.url, 53django_sorcery.db.utils, 54django_sorcery.exceptions, 77django_sorcery.fields, 78django_sorcery.forms, 79django_sorcery.formsets, 54django_sorcery.formsets.base, 54django_sorcery.formsets.inline, 55django_sorcery.management, 56django_sorcery.management.alembic, 61django_sorcery.management.base, 62django_sorcery.management.commands, 56django_sorcery.management.commands.sorcery,

56django_sorcery.management.commands.sorcery_createall,

57django_sorcery.management.commands.sorcery_current,

57django_sorcery.management.commands.sorcery_downgrade,

58django_sorcery.management.commands.sorcery_dropall,

58django_sorcery.management.commands.sorcery_heads,

59django_sorcery.management.commands.sorcery_history,

59django_sorcery.management.commands.sorcery_revision,

60django_sorcery.management.commands.sorcery_stamp,

60django_sorcery.management.commands.sorcery_upgrade,

60django_sorcery.pytest_plugin, 80django_sorcery.routers, 81django_sorcery.shortcuts, 82django_sorcery.testing, 83django_sorcery.utils, 83django_sorcery.validators, 62django_sorcery.validators.base, 62django_sorcery.validators.runner, 65django_sorcery.views, 65django_sorcery.views.base, 65django_sorcery.views.detail, 67django_sorcery.views.edit, 68django_sorcery.views.list, 70django_sorcery.viewsets, 70django_sorcery.viewsets.base, 74django_sorcery.viewsets.mixins, 75

87

Page 92: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

88 Python Module Index

Page 93: Django Sorcery Documentation

Index

Aabsolute_max (django_sorcery.formsets.base.BaseModelFormSet

attribute), 54action() (in module django_sorcery.routers), 82add() (django_sorcery.db.sqlalchemy.SQLAlchemy

method), 50add_all() (django_sorcery.db.sqlalchemy.SQLAlchemy

method), 50add_arguments() (django_sorcery.management.commands.sorcery_createall.CreateAll

method), 57add_arguments() (django_sorcery.management.commands.sorcery_current.Current

method), 58add_arguments() (django_sorcery.management.commands.sorcery_downgrade.Downgrade

method), 58add_arguments() (django_sorcery.management.commands.sorcery_dropall.DropAll

method), 58add_arguments() (django_sorcery.management.commands.sorcery_heads.ShowHeads

method), 59add_arguments() (django_sorcery.management.commands.sorcery_history.History

method), 59add_arguments() (django_sorcery.management.commands.sorcery_revision.Revision

method), 60add_arguments() (django_sorcery.management.commands.sorcery_stamp.Stamp

method), 60add_arguments() (django_sorcery.management.commands.sorcery_upgrade.Upgrade

method), 61add_fields() (django_sorcery.formsets.base.BaseModelFormSet

method), 54after_commit() (in module

django_sorcery.db.session), 48after_flush() (in module

django_sorcery.db.session), 48after_rollback() (in module

django_sorcery.db.session), 48AlembicAppConfig (class in

django_sorcery.management.alembic), 61AlembicCommand (class in

django_sorcery.management.alembic), 61allow_empty (django_sorcery.validators.base.ValidateEmptyWhen

attribute), 63allow_empty (django_sorcery.validators.base.ValidateNotEmptyWhen

attribute), 63allow_empty (django_sorcery.views.base.BaseMultipleObjectMixin

attribute), 65app (django_sorcery.management.alembic.AlembicAppConfig

attribute), 61app_config (django_sorcery.db.meta.model.model_info

attribute), 33app_label (django_sorcery.db.meta.model.model_info

attribute), 33apply_limit_choices_to_form_field() (in

module django_sorcery.forms), 80args (django_sorcery.db.query.Operation attribute), 45args() (django_sorcery.db.sqlalchemy.SQLAlchemy

method), 50as_dict() (django_sorcery.db.composites.BaseComposite

method), 36as_dict() (django_sorcery.db.models.Base method),

43as_dict() (django_sorcery.db.sqlalchemy.SQLAlchemy.BaseComposite

method), 49as_view() (django_sorcery.viewsets.base.GenericViewSet

class method), 74as_view() (django_sorcery.viewsets.GenericViewSet

class method), 70atomic() (django_sorcery.db.sqlalchemy.SQLAlchemy

method), 50atomic() (django_sorcery.db.utils.dbdict method), 54attname (django_sorcery.db.meta.column.column_info

attribute), 30attribute (django_sorcery.db.meta.column.column_info

attribute), 30attribute (django_sorcery.db.meta.composite.composite_info

attribute), 33attribute (django_sorcery.db.meta.relations.relation_info

attribute), 35autocoerce() (in module django_sorcery.db.models),

43autocoerce_properties() (in module

89

Page 94: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

django_sorcery.db.models), 43autocommit (django_sorcery.db.sqlalchemy.SQLAlchemy

attribute), 50autoflush (django_sorcery.db.sqlalchemy.SQLAlchemy

attribute), 50

BBase (class in django_sorcery.db.models), 42base_fields (django_sorcery.forms.ModelForm at-

tribute), 80BaseComposite (class in

django_sorcery.db.composites), 36BaseCreateView (class in

django_sorcery.views.edit), 68BaseDeleteView (class in

django_sorcery.views.edit), 68BaseDetailView (class in

django_sorcery.views.detail), 67BaseFormView (class in django_sorcery.views.edit),

68BaseInlineFormSet (class in

django_sorcery.formsets.inline), 55BaseListView (class in django_sorcery.views.list), 70BaseMeta (class in django_sorcery.db.models), 43BaseMiddleware (class in

django_sorcery.db.middleware), 41BaseModelForm (class in django_sorcery.forms), 79BaseModelFormSet (class in

django_sorcery.formsets.base), 54BaseMultipleObjectMixin (class in

django_sorcery.views.base), 65BaseRouter (class in django_sorcery.routers), 81BaseSingleObjectMixin (class in

django_sorcery.views.base), 66BaseUpdateView (class in

django_sorcery.views.edit), 68before_commit() (in module

django_sorcery.db.session), 48before_flush() (in module

django_sorcery.db.session), 48begin() (django_sorcery.db.sqlalchemy.SQLAlchemy

method), 50begin_nested() (django_sorcery.db.sqlalchemy.SQLAlchemy

method), 50BigIntegerField (class in

django_sorcery.db.fields), 36BinaryField (class in django_sorcery.db.fields), 37bind (django_sorcery.db.sqlalchemy.SQLAlchemy at-

tribute), 50bind_mapper() (django_sorcery.db.sqlalchemy.SQLAlchemy

method), 50bind_table() (django_sorcery.db.sqlalchemy.SQLAlchemy

method), 50boolean() (in module django_sorcery.db.url), 53

boolean_column_info (class indjango_sorcery.db.meta.column), 29

BooleanField (class in django_sorcery.db.fields), 37bound_data() (django_sorcery.fields.EnumField

method), 78bulk_insert_mappings()

(django_sorcery.db.sqlalchemy.SQLAlchemymethod), 50

bulk_save_objects()(django_sorcery.db.sqlalchemy.SQLAlchemymethod), 50

bulk_update_mappings()(django_sorcery.db.sqlalchemy.SQLAlchemymethod), 50

CCharField (class in django_sorcery.db.fields), 37choice() (django_sorcery.fields.ModelChoiceIterator

method), 79choice_column_info (class in

django_sorcery.db.meta.column), 29choices (django_sorcery.db.meta.column.column_info

attribute), 30choices (django_sorcery.fields.ModelChoiceField at-

tribute), 78clean() (django_sorcery.db.meta.column.column_info

method), 30clean() (django_sorcery.db.mixins.CleanMixin

method), 42clean_fields() (django_sorcery.db.meta.composite.composite_info

method), 33clean_fields() (django_sorcery.db.meta.model.model_info

method), 33clean_fields() (django_sorcery.db.mixins.CleanMixin

method), 42clean_nested_fields()

(django_sorcery.db.meta.model.model_infomethod), 33

clean_nested_fields()(django_sorcery.db.mixins.CleanMixinmethod), 42

clean_relation_fields()(django_sorcery.db.meta.model.model_infomethod), 34

clean_relation_fields()(django_sorcery.db.mixins.CleanMixinmethod), 42

CleanMixin (class in django_sorcery.db.mixins), 41cleanup() (django_sorcery.db.signals.ScopedSignal

method), 49clear() (django_sorcery.db.profiler.SQLAlchemyProfiler

method), 44clone() (in module django_sorcery.db.models), 43

90 Index

Page 95: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

close() (django_sorcery.db.sqlalchemy.SQLAlchemymethod), 50

close_all() (django_sorcery.db.sqlalchemy.SQLAlchemymethod), 50

code (django_sorcery.validators.base.ValidateCantRemoveattribute), 63

code (django_sorcery.validators.base.ValidateEmptyWhenattribute), 63

code (django_sorcery.validators.base.ValidateNotEmptyWhenattribute), 64

code (django_sorcery.validators.base.ValidateOnlyOneOfattribute), 64

code (django_sorcery.validators.base.ValidateTogetherModelFieldsattribute), 64

code (django_sorcery.validators.base.ValidateUniqueattribute), 65

code (django_sorcery.validators.base.ValidateValue at-tribute), 65

coercer (django_sorcery.db.meta.column.column_infoattribute), 30

coercer (django_sorcery.db.meta.column.date_column_infoattribute), 31

coercer (django_sorcery.db.meta.column.datetime_column_infoattribute), 31

column (django_sorcery.db.meta.column.column_infoattribute), 30

column_info (class indjango_sorcery.db.meta.column), 30

column_properties(django_sorcery.db.meta.model.model_infoattribute), 34

Command (class in django_sorcery.management.commands.sorcery),56

Command (in moduledjango_sorcery.management.commands.sorcery_createall),57

Command (in moduledjango_sorcery.management.commands.sorcery_current),57

Command (in moduledjango_sorcery.management.commands.sorcery_downgrade),58

Command (in moduledjango_sorcery.management.commands.sorcery_dropall),58

Command (in moduledjango_sorcery.management.commands.sorcery_heads),59

Command (in moduledjango_sorcery.management.commands.sorcery_history),59

Command (in moduledjango_sorcery.management.commands.sorcery_revision),60

Command (in moduledjango_sorcery.management.commands.sorcery_stamp),60

Command (in moduledjango_sorcery.management.commands.sorcery_upgrade),60

Command.Meta (class indjango_sorcery.management.commands.sorcery),56

commands (django_sorcery.management.base.NamespacedCommandattribute), 62

commit() (django_sorcery.db.middleware.SQLAlchemyDBMiddlewaremethod), 41

commit() (django_sorcery.db.sqlalchemy.SQLAlchemymethod), 50

commit() (django_sorcery.db.utils.dbdict method), 54CommitException, 83composite_info (class in

django_sorcery.db.meta.composite), 33CompositeField (class in

django_sorcery.db.composites), 36composites (django_sorcery.db.meta.model.model_info

attribute), 34concrete_fields (django_sorcery.db.meta.model.model_info

attribute), 34config (django_sorcery.management.alembic.AlembicAppConfig

attribute), 61confirm_destroy()

(django_sorcery.viewsets.DeleteModelMixinmethod), 72

confirm_destroy()(django_sorcery.viewsets.mixins.DeleteModelMixinmethod), 75

connection() (django_sorcery.db.sqlalchemy.SQLAlchemymethod), 50

connection_callable(django_sorcery.db.sqlalchemy.SQLAlchemyattribute), 50

context_object_name(django_sorcery.views.base.SQLAlchemyMixinattribute), 66

context_object_name(django_sorcery.views.list.MultipleObjectMixinattribute), 70

counts (django_sorcery.db.profiler.SQLAlchemyProfilerattribute), 44

create() (django_sorcery.viewsets.CreateModelMixinmethod), 71

create() (django_sorcery.viewsets.mixins.CreateModelMixinmethod), 75

create_all() (django_sorcery.db.sqlalchemy.SQLAlchemymethod), 50

create_parser() (django_sorcery.management.base.NamespacedCommandmethod), 62

Index 91

Page 96: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

CreateAll (class indjango_sorcery.management.commands.sorcery_createall),57

createall (django_sorcery.management.commands.sorcery.Commandattribute), 56

CreateModelMixin (class indjango_sorcery.viewsets), 71

CreateModelMixin (class indjango_sorcery.viewsets.mixins), 75

CreateView (class in django_sorcery.views.edit), 68Current (class in django_sorcery.management.commands.sorcery_current),

57current (django_sorcery.management.commands.sorcery.Command

attribute), 57

Ddate_column_info (class in

django_sorcery.db.meta.column), 31DateField (class in django_sorcery.db.fields), 37datetime_column_info (class in

django_sorcery.db.meta.column), 31DateTimeField (class in django_sorcery.db.fields),

37db (django_sorcery.db.middleware.SQLAlchemyDBMiddleware

attribute), 41db (django_sorcery.db.middleware.SQLAlchemyMiddleware

attribute), 41db (django_sorcery.management.alembic.AlembicAppConfig

attribute), 61dbdict (class in django_sorcery.db.utils), 54decimal_places (django_sorcery.db.meta.column.numeric_column_info

attribute), 32DecimalField (class in django_sorcery.db.fields), 38declare_first_relationships_handler()

(in module django_sorcery.db.relations), 48declared_fields (django_sorcery.forms.ModelForm

attribute), 80default (django_sorcery.db.meta.column.column_info

attribute), 30default_error_messages

(django_sorcery.db.meta.column.column_infoattribute), 30

default_error_messages(django_sorcery.fields.ModelChoiceFieldattribute), 78

default_error_messages(django_sorcery.fields.ModelMultipleChoiceFieldattribute), 79

default_form_class(django_sorcery.db.meta.column.choice_column_infoattribute), 30

default_form_class(django_sorcery.db.meta.column.column_infoattribute), 30

default_form_class(django_sorcery.db.meta.column.date_column_infoattribute), 31

default_form_class(django_sorcery.db.meta.column.datetime_column_infoattribute), 31

default_form_class(django_sorcery.db.meta.column.enum_column_infoattribute), 31

default_form_class(django_sorcery.db.meta.column.float_column_infoattribute), 31

default_form_class(django_sorcery.db.meta.column.integer_column_infoattribute), 32

default_form_class(django_sorcery.db.meta.column.interval_column_infoattribute), 32

default_form_class(django_sorcery.db.meta.column.numeric_column_infoattribute), 32

default_form_class(django_sorcery.db.meta.column.string_column_infoattribute), 32

default_form_class(django_sorcery.db.meta.column.time_column_infoattribute), 32

default_validators(django_sorcery.db.fields.BigIntegerFieldattribute), 36

default_validators(django_sorcery.db.fields.EmailField at-tribute), 38

default_validators(django_sorcery.db.fields.Field attribute),39

default_validators(django_sorcery.db.fields.IntegerField at-tribute), 39

default_validators(django_sorcery.db.fields.SlugField attribute),40

default_validators(django_sorcery.db.fields.SmallIntegerFieldattribute), 40

default_validators(django_sorcery.db.fields.URLField attribute),40

delete() (django_sorcery.db.sqlalchemy.SQLAlchemymethod), 51

delete() (django_sorcery.views.edit.DeletionMixinmethod), 69

delete_existing()(django_sorcery.formsets.base.BaseModelFormSet

92 Index

Page 97: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

method), 55deleted (django_sorcery.db.sqlalchemy.SQLAlchemy

attribute), 51DeleteModelMixin (class in

django_sorcery.viewsets), 72DeleteModelMixin (class in

django_sorcery.viewsets.mixins), 75DeleteView (class in django_sorcery.views.edit), 68DeletionMixin (class in django_sorcery.views.edit),

69deserialize() (in module

django_sorcery.db.models), 43destroy() (django_sorcery.viewsets.DeleteModelMixin

method), 72destroy() (django_sorcery.viewsets.mixins.DeleteModelMixin

method), 75destroy_success_url

(django_sorcery.viewsets.DeleteModelMixinattribute), 72

destroy_success_url(django_sorcery.viewsets.mixins.DeleteModelMixinattribute), 75

detail (django_sorcery.routers.DynamicRoute at-tribute), 81

detail (django_sorcery.routers.Route attribute), 81DetailView (class in django_sorcery.views.detail), 67direction (django_sorcery.db.meta.relations.relation_info

attribute), 35dirty (django_sorcery.db.sqlalchemy.SQLAlchemy at-

tribute), 51dispatch (django_sorcery.db.sqlalchemy.SQLAlchemy

attribute), 51display_version()

(django_sorcery.management.commands.sorcery_current.Currentmethod), 58

django_sorcery (module), 26django_sorcery.db (module), 26django_sorcery.db.alembic (module), 29django_sorcery.db.alembic.base (module),

29django_sorcery.db.alembic.signals (mod-

ule), 29django_sorcery.db.composites (module), 36django_sorcery.db.fields (module), 36django_sorcery.db.meta (module), 29django_sorcery.db.meta.base (module), 29django_sorcery.db.meta.column (module), 29django_sorcery.db.meta.composite (mod-

ule), 33django_sorcery.db.meta.model (module), 33django_sorcery.db.meta.relations (mod-

ule), 35django_sorcery.db.middleware (module), 41django_sorcery.db.mixins (module), 41

django_sorcery.db.models (module), 42django_sorcery.db.profiler (module), 44django_sorcery.db.query (module), 45django_sorcery.db.relations (module), 47django_sorcery.db.session (module), 48django_sorcery.db.signals (module), 49django_sorcery.db.sqlalchemy (module), 49django_sorcery.db.transaction (module), 52django_sorcery.db.url (module), 53django_sorcery.db.utils (module), 54django_sorcery.exceptions (module), 77django_sorcery.fields (module), 78django_sorcery.forms (module), 79django_sorcery.formsets (module), 54django_sorcery.formsets.base (module), 54django_sorcery.formsets.inline (module),

55django_sorcery.management (module), 56django_sorcery.management.alembic (mod-

ule), 61django_sorcery.management.base (module),

62django_sorcery.management.commands (mod-

ule), 56django_sorcery.management.commands.sorcery

(module), 56django_sorcery.management.commands.sorcery_createall

(module), 57django_sorcery.management.commands.sorcery_current

(module), 57django_sorcery.management.commands.sorcery_downgrade

(module), 58django_sorcery.management.commands.sorcery_dropall

(module), 58django_sorcery.management.commands.sorcery_heads

(module), 59django_sorcery.management.commands.sorcery_history

(module), 59django_sorcery.management.commands.sorcery_revision

(module), 60django_sorcery.management.commands.sorcery_stamp

(module), 60django_sorcery.management.commands.sorcery_upgrade

(module), 60django_sorcery.pytest_plugin (module), 80django_sorcery.routers (module), 81django_sorcery.shortcuts (module), 82django_sorcery.testing (module), 83django_sorcery.utils (module), 83django_sorcery.validators (module), 62django_sorcery.validators.base (module),

62django_sorcery.validators.runner (mod-

ule), 65

Index 93

Page 98: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

django_sorcery.views (module), 65django_sorcery.views.base (module), 65django_sorcery.views.detail (module), 67django_sorcery.views.edit (module), 68django_sorcery.views.list (module), 70django_sorcery.viewsets (module), 70django_sorcery.viewsets.base (module), 74django_sorcery.viewsets.mixins (module),

75Downgrade (class in

django_sorcery.management.commands.sorcery_downgrade),58

downgrade (django_sorcery.management.commands.sorcery.Commandattribute), 57

downgrade() (django_sorcery.management.commands.sorcery_downgrade.Downgrademethod), 58

drop_all() (django_sorcery.db.sqlalchemy.SQLAlchemymethod), 51

DropAll (class in django_sorcery.management.commands.sorcery_dropall),58

dropall (django_sorcery.management.commands.sorcery.Commandattribute), 57

duration (django_sorcery.db.profiler.Query attribute),44

duration (django_sorcery.db.profiler.SQLAlchemyProfilerattribute), 44

DurationField (class in django_sorcery.db.fields),38

DynamicRoute (class in django_sorcery.routers), 81

Eedit() (django_sorcery.viewsets.mixins.UpdateModelMixin

method), 77edit() (django_sorcery.viewsets.UpdateModelMixin

method), 73EmailField (class in django_sorcery.db.fields), 38empty_value (django_sorcery.fields.EnumField at-

tribute), 78empty_values (django_sorcery.db.meta.column.column_info

attribute), 30enable_baked_queries

(django_sorcery.db.sqlalchemy.SQLAlchemyattribute), 51

enable_relationship_loading()(django_sorcery.db.sqlalchemy.SQLAlchemymethod), 51

end() (django_sorcery.testing.Transact method), 83engine (django_sorcery.db.sqlalchemy.SQLAlchemy at-

tribute), 51enum_column_info (class in

django_sorcery.db.meta.column), 31EnumField (class in django_sorcery.db.fields), 38EnumField (class in django_sorcery.fields), 78

error_messages (django_sorcery.db.meta.column.column_infoattribute), 30

escape_curly_brackets() (in moduledjango_sorcery.routers), 82

execute() (django_sorcery.db.sqlalchemy.SQLAlchemymethod), 51

expire() (django_sorcery.db.sqlalchemy.SQLAlchemymethod), 51

expire_all() (django_sorcery.db.sqlalchemy.SQLAlchemymethod), 51

expire_on_commit (django_sorcery.db.sqlalchemy.SQLAlchemyattribute), 51

expunge() (django_sorcery.db.sqlalchemy.SQLAlchemymethod), 51

expunge_all() (django_sorcery.db.sqlalchemy.SQLAlchemymethod), 51

FField (class in django_sorcery.db.fields), 38field_kwargs (django_sorcery.db.meta.column.column_info

attribute), 30field_kwargs (django_sorcery.db.meta.relations.relation_info

attribute), 35field_names (django_sorcery.db.meta.composite.composite_info

attribute), 33field_names (django_sorcery.db.meta.model.model_info

attribute), 34fields (django_sorcery.db.meta.model.model_info at-

tribute), 34fields (django_sorcery.views.edit.ModelFormMixin

attribute), 69fields (django_sorcery.viewsets.mixins.ModelFormMixin

attribute), 76fields (django_sorcery.viewsets.ModelFormMixin at-

tribute), 73fields_for_model() (in module

django_sorcery.forms), 80filter() (django_sorcery.db.query.Query method), 45float_column_info (class in

django_sorcery.db.meta.column), 31FloatField (class in django_sorcery.db.fields), 39flush() (django_sorcery.db.middleware.SQLAlchemyDBMiddleware

method), 41flush() (django_sorcery.db.sqlalchemy.SQLAlchemy

method), 51flush() (django_sorcery.db.utils.dbdict method), 54foreign_keys (django_sorcery.db.meta.relations.relation_info

attribute), 35form_class (django_sorcery.db.fields.BigIntegerField

attribute), 36form_class (django_sorcery.db.fields.BooleanField

attribute), 37form_class (django_sorcery.db.fields.CharField at-

tribute), 37

94 Index

Page 99: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

form_class (django_sorcery.db.fields.DateField at-tribute), 37

form_class (django_sorcery.db.fields.DateTimeFieldattribute), 38

form_class (django_sorcery.db.fields.DecimalFieldattribute), 38

form_class (django_sorcery.db.fields.DurationFieldattribute), 38

form_class (django_sorcery.db.fields.EmailField at-tribute), 38

form_class (django_sorcery.db.fields.Field attribute),39

form_class (django_sorcery.db.fields.FloatField at-tribute), 39

form_class (django_sorcery.db.fields.IntegerField at-tribute), 39

form_class (django_sorcery.db.fields.NullBooleanFieldattribute), 39

form_class (django_sorcery.db.fields.SlugField at-tribute), 40

form_class (django_sorcery.db.fields.SmallIntegerFieldattribute), 40

form_class (django_sorcery.db.fields.TextFieldattribute), 40

form_class (django_sorcery.db.fields.TimeField at-tribute), 40

form_class (django_sorcery.db.fields.URLField at-tribute), 40

form_class (django_sorcery.db.meta.column.column_infoattribute), 30

form_class (django_sorcery.viewsets.mixins.ModelFormMixinattribute), 76

form_class (django_sorcery.viewsets.ModelFormMixinattribute), 73

form_invalid() (django_sorcery.viewsets.mixins.ModelFormMixinmethod), 76

form_invalid() (django_sorcery.viewsets.ModelFormMixinmethod), 73

form_valid() (django_sorcery.views.edit.ModelFormMixinmethod), 69

form_valid() (django_sorcery.viewsets.mixins.ModelFormMixinmethod), 76

form_valid() (django_sorcery.viewsets.ModelFormMixinmethod), 73

formfield() (django_sorcery.db.meta.column.column_infomethod), 30

formfield() (django_sorcery.db.meta.relations.relation_infomethod), 35

FormView (class in django_sorcery.views.edit), 69full_clean() (django_sorcery.db.meta.composite.composite_info

method), 33full_clean() (django_sorcery.db.meta.model.model_info

method), 34full_clean() (django_sorcery.db.mixins.CleanMixin

method), 42full_clean_flush_handler() (in module

django_sorcery.db.models), 43future (django_sorcery.db.sqlalchemy.SQLAlchemy at-

tribute), 51

Ggenerate_migration()

(django_sorcery.management.commands.sorcery_revision.Revisionmethod), 60

GenericViewSet (class in django_sorcery.viewsets),70

GenericViewSet (class indjango_sorcery.viewsets.base), 74

get() (django_sorcery.db.query.Query method), 46get() (django_sorcery.db.sqlalchemy.SQLAlchemy

method), 51get() (django_sorcery.db.utils.dbdict method), 54get() (django_sorcery.views.detail.BaseDetailView

method), 67get() (django_sorcery.views.edit.BaseCreateView

method), 68get() (django_sorcery.views.edit.BaseUpdateView

method), 68get() (django_sorcery.views.edit.ProcessFormView

method), 69get() (django_sorcery.views.list.BaseListView

method), 70get_allow_empty()

(django_sorcery.views.base.BaseMultipleObjectMixinmethod), 66

get_app_config() (django_sorcery.management.alembic.AlembicCommandmethod), 61

get_app_version_path()(django_sorcery.management.alembic.AlembicCommandmethod), 61

get_args() (in module django_sorcery.utils), 83get_bind() (django_sorcery.db.sqlalchemy.SQLAlchemy

method), 51get_bound_field()

(django_sorcery.fields.ModelChoiceFieldmethod), 78

get_column_kwargs()(django_sorcery.db.fields.BooleanFieldmethod), 37

get_column_kwargs()(django_sorcery.db.fields.Field method),39

get_column_kwargs()(django_sorcery.db.fields.NullBooleanFieldmethod), 39

get_common_config()(django_sorcery.management.alembic.AlembicCommandmethod), 62

Index 95

Page 100: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

get_config_script()(django_sorcery.management.alembic.AlembicCommandmethod), 62

get_context_data()(django_sorcery.views.detail.SingleObjectMixinmethod), 67

get_context_data()(django_sorcery.views.list.MultipleObjectMixinmethod), 70

get_context_object_name()(django_sorcery.views.detail.SingleObjectMixinmethod), 67

get_context_object_name()(django_sorcery.views.list.MultipleObjectMixinmethod), 70

get_create_context_data()(django_sorcery.viewsets.CreateModelMixinmethod), 72

get_create_context_data()(django_sorcery.viewsets.mixins.CreateModelMixinmethod), 75

get_default_base_name()(django_sorcery.routers.BaseRouter method),81

get_default_base_name()(django_sorcery.routers.SimpleRoutermethod), 82

get_default_prefix()(django_sorcery.formsets.inline.BaseInlineFormSetclass method), 55

get_destroy_context_data()(django_sorcery.viewsets.DeleteModelMixinmethod), 72

get_destroy_context_data()(django_sorcery.viewsets.mixins.DeleteModelMixinmethod), 75

get_destroy_success_url()(django_sorcery.viewsets.DeleteModelMixinmethod), 72

get_destroy_success_url()(django_sorcery.viewsets.mixins.DeleteModelMixinmethod), 75

get_detail_context_data()(django_sorcery.viewsets.mixins.RetrieveModelMixinmethod), 77

get_detail_context_data()(django_sorcery.viewsets.RetrieveModelMixinmethod), 73

get_detail_context_object_name()(django_sorcery.viewsets.mixins.RetrieveModelMixinmethod), 77

get_detail_context_object_name()(django_sorcery.viewsets.RetrieveModelMixinmethod), 73

get_extra_actions()(django_sorcery.viewsets.base.GenericViewSetclass method), 74

get_extra_actions()(django_sorcery.viewsets.GenericViewSetclass method), 71

get_field() (django_sorcery.db.meta.model.model_infomethod), 34

get_form_class() (django_sorcery.db.fields.EnumFieldmethod), 38

get_form_class() (django_sorcery.db.fields.Fieldmethod), 39

get_form_class() (django_sorcery.db.meta.relations.relation_infomethod), 35

get_form_class() (django_sorcery.views.edit.ModelFormMixinmethod), 69

get_form_class() (django_sorcery.viewsets.mixins.ModelFormMixinmethod), 76

get_form_class() (django_sorcery.viewsets.ModelFormMixinmethod), 73

get_form_context_data()(django_sorcery.viewsets.mixins.ModelFormMixinmethod), 76

get_form_context_data()(django_sorcery.viewsets.ModelFormMixinmethod), 73

get_form_kwargs()(django_sorcery.views.edit.ModelFormMixinmethod), 69

get_form_kwargs()(django_sorcery.viewsets.mixins.ModelFormMixinmethod), 76

get_form_kwargs()(django_sorcery.viewsets.ModelFormMixinmethod), 73

get_key() (django_sorcery.db.meta.model.model_infomethod), 34

get_limit_choices_to()(django_sorcery.fields.ModelChoiceFieldmethod), 78

get_list_context_data()(django_sorcery.viewsets.ListModelMixinmethod), 72

get_list_context_data()(django_sorcery.viewsets.mixins.ListModelMixinmethod), 76

get_list_context_object_name()(django_sorcery.viewsets.ListModelMixinmethod), 72

get_list_context_object_name()(django_sorcery.viewsets.mixins.ListModelMixinmethod), 76

get_list_or_404() (in moduledjango_sorcery.shortcuts), 82

96 Index

Page 101: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

get_lookup_regex()(django_sorcery.routers.SimpleRoutermethod), 82

get_method_map() (django_sorcery.routers.SimpleRoutermethod), 82

get_model() (django_sorcery.views.base.SQLAlchemyMixinclass method), 66

get_model_template_name()(django_sorcery.views.base.SQLAlchemyMixinmethod), 67

get_nested_transaction()(django_sorcery.db.sqlalchemy.SQLAlchemymethod), 51

get_object() (django_sorcery.fields.ModelChoiceFieldmethod), 78

get_object() (django_sorcery.views.base.BaseSingleObjectMixinmethod), 66

get_object_or_404() (in moduledjango_sorcery.shortcuts), 82

get_ordering() (django_sorcery.views.base.BaseMultipleObjectMixinmethod), 66

get_paginate_by()(django_sorcery.views.base.BaseMultipleObjectMixinmethod), 66

get_paginate_orphans()(django_sorcery.views.base.BaseMultipleObjectMixinmethod), 66

get_paginator() (django_sorcery.views.base.BaseMultipleObjectMixinmethod), 66

get_query_options()(django_sorcery.views.base.SQLAlchemyMixinmethod), 67

get_queryset() (django_sorcery.formsets.base.BaseModelFormSetmethod), 55

get_queryset() (django_sorcery.views.base.BaseMultipleObjectMixinmethod), 66

get_queryset() (django_sorcery.views.base.SQLAlchemyMixinmethod), 67

get_routes() (django_sorcery.routers.SimpleRoutermethod), 82

get_session() (django_sorcery.views.base.SQLAlchemyMixinmethod), 67

get_settings() (in module django_sorcery.db.url),53

get_slug_field() (django_sorcery.views.base.BaseSingleObjectMixinmethod), 66

get_success_url()(django_sorcery.views.edit.DeletionMixinmethod), 69

get_success_url()(django_sorcery.views.edit.ModelFormMixinmethod), 69

get_success_url()(django_sorcery.viewsets.mixins.ModelFormMixin

method), 76get_success_url()

(django_sorcery.viewsets.ModelFormMixinmethod), 73

get_template_names()(django_sorcery.views.detail.SingleObjectTemplateResponseMixinmethod), 67

get_template_names()(django_sorcery.views.list.MultipleObjectTemplateResponseMixinmethod), 70

get_template_names()(django_sorcery.viewsets.base.GenericViewSetmethod), 74

get_template_names()(django_sorcery.viewsets.GenericViewSetmethod), 71

get_transaction()(django_sorcery.db.sqlalchemy.SQLAlchemymethod), 51

get_type() (django_sorcery.db.fields.EnumFieldmethod), 38

get_type() (django_sorcery.db.fields.Field method),39

get_type_class() (django_sorcery.db.fields.Fieldmethod), 39

get_type_kwargs()(django_sorcery.db.fields.BooleanFieldmethod), 37

get_type_kwargs()(django_sorcery.db.fields.CharField method),37

get_type_kwargs()(django_sorcery.db.fields.DecimalFieldmethod), 38

get_type_kwargs()(django_sorcery.db.fields.EnumField method),38

get_type_kwargs() (django_sorcery.db.fields.Fieldmethod), 39

get_type_kwargs()(django_sorcery.db.fields.FloatField method),39

get_update_context_data()(django_sorcery.viewsets.mixins.UpdateModelMixinmethod), 77

get_update_context_data()(django_sorcery.viewsets.UpdateModelMixinmethod), 74

get_url_kwargs() (django_sorcery.viewsets.mixins.RetrieveModelMixinmethod), 77

get_url_kwargs() (django_sorcery.viewsets.RetrieveModelMixinmethod), 73

get_urls() (django_sorcery.routers.BaseRoutermethod), 81

Index 97

Page 102: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

get_urls() (django_sorcery.routers.SimpleRoutermethod), 82

get_validators() (django_sorcery.db.fields.CharFieldmethod), 37

get_validators() (django_sorcery.db.fields.DecimalFieldmethod), 38

get_validators() (django_sorcery.db.fields.Fieldmethod), 39

Hhandle() (django_sorcery.management.commands.sorcery_createall.CreateAll

method), 57handle() (django_sorcery.management.commands.sorcery_current.Current

method), 58handle() (django_sorcery.management.commands.sorcery_downgrade.Downgrade

method), 58handle() (django_sorcery.management.commands.sorcery_dropall.DropAll

method), 59handle() (django_sorcery.management.commands.sorcery_heads.ShowHeads

method), 59handle() (django_sorcery.management.commands.sorcery_history.History

method), 59handle() (django_sorcery.management.commands.sorcery_revision.Revision

method), 60handle() (django_sorcery.management.commands.sorcery_stamp.Stamp

method), 60handle() (django_sorcery.management.commands.sorcery_upgrade.Upgrade

method), 61hash_key (django_sorcery.db.sqlalchemy.SQLAlchemy

attribute), 51header_results (django_sorcery.db.profiler.SQLAlchemyProfilingMiddleware

attribute), 45heads (django_sorcery.management.commands.sorcery.Command

attribute), 57help (django_sorcery.management.commands.sorcery.Command

attribute), 57help (django_sorcery.management.commands.sorcery_createall.CreateAll

attribute), 57help (django_sorcery.management.commands.sorcery_current.Current

attribute), 58help (django_sorcery.management.commands.sorcery_downgrade.Downgrade

attribute), 58help (django_sorcery.management.commands.sorcery_dropall.DropAll

attribute), 59help (django_sorcery.management.commands.sorcery_heads.ShowHeads

attribute), 59help (django_sorcery.management.commands.sorcery_history.History

attribute), 59help (django_sorcery.management.commands.sorcery_revision.Revision

attribute), 60help (django_sorcery.management.commands.sorcery_stamp.Stamp

attribute), 60help (django_sorcery.management.commands.sorcery_upgrade.Upgrade

attribute), 61

help_text (django_sorcery.db.meta.column.column_infoattribute), 30

hidden_widget (django_sorcery.fields.ModelMultipleChoiceFieldattribute), 79

History (class in django_sorcery.management.commands.sorcery_history),59

history (django_sorcery.management.commands.sorcery.Commandattribute), 57

hook() (django_sorcery.testing.Transact method), 83

IIdentity (in module django_sorcery.db.meta.model),

33identity_key() (django_sorcery.db.sqlalchemy.SQLAlchemy

method), 51identity_key_from_dict()

(django_sorcery.db.meta.model.model_infomethod), 34

identity_key_from_instance()(django_sorcery.db.meta.model.model_infomethod), 34

identity_map (django_sorcery.db.sqlalchemy.SQLAlchemyattribute), 51

importable() (in module django_sorcery.db.url), 53importable_list() (in module

django_sorcery.db.url), 53importable_list_tuples() (in module

django_sorcery.db.url), 53in_nested_transaction()

(django_sorcery.db.sqlalchemy.SQLAlchemymethod), 51

in_transaction() (django_sorcery.db.sqlalchemy.SQLAlchemymethod), 51

include_object() (in moduledjango_sorcery.db.alembic.signals), 29

index_foreign_keys() (in moduledjango_sorcery.db.utils), 54

info (django_sorcery.db.sqlalchemy.SQLAlchemy at-tribute), 51

initial_form_count()(django_sorcery.formsets.base.BaseModelFormSetmethod), 55

initial_form_count()(django_sorcery.formsets.inline.BaseInlineFormSetmethod), 55

initkwargs (django_sorcery.routers.DynamicRouteattribute), 81

initkwargs (django_sorcery.routers.Route attribute),81

inlineformset_factory() (in moduledjango_sorcery.formsets.inline), 56

inspector (django_sorcery.db.sqlalchemy.SQLAlchemyattribute), 51

98 Index

Page 103: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

instant_defaults() (in moduledjango_sorcery.db.models), 44

instrument() (in moduledjango_sorcery.db.sqlalchemy), 52

instrument_class()(django_sorcery.db.composites.CompositeFieldmethod), 36

instrument_class()(django_sorcery.db.sqlalchemy.SQLAlchemy.CompositeFieldmethod), 50

integer() (in module django_sorcery.db.url), 53integer_column_info (class in

django_sorcery.db.meta.column), 31IntegerField (class in django_sorcery.db.fields), 39interval_column_info (class in

django_sorcery.db.meta.column), 32invalidate() (django_sorcery.db.sqlalchemy.SQLAlchemy

method), 51is_active (django_sorcery.db.sqlalchemy.SQLAlchemy

attribute), 51is_modified() (django_sorcery.db.sqlalchemy.SQLAlchemy

method), 51is_relation (django_sorcery.db.meta.column.column_info

attribute), 30is_valid() (django_sorcery.forms.BaseModelForm

method), 79is_valid() (django_sorcery.validators.runner.ValidationRunner

method), 65iterator (django_sorcery.fields.ModelChoiceField at-

tribute), 78

Kkwargs (django_sorcery.db.query.Operation attribute),

45

Llabel (django_sorcery.db.meta.column.column_info at-

tribute), 30label (django_sorcery.db.meta.model.model_info at-

tribute), 34label_from_instance()

(django_sorcery.fields.ModelChoiceFieldmethod), 78

label_lower (django_sorcery.db.meta.model.model_infoattribute), 34

length_is_required(django_sorcery.db.fields.BinaryField at-tribute), 37

length_is_required(django_sorcery.db.fields.CharField attribute),37

length_is_required(django_sorcery.db.fields.TextField attribute),40

list() (django_sorcery.viewsets.ListModelMixinmethod), 72

list() (django_sorcery.viewsets.mixins.ListModelMixinmethod), 76

ListModelMixin (class in django_sorcery.viewsets),72

ListModelMixin (class indjango_sorcery.viewsets.mixins), 76

ListView (class in django_sorcery.views.list), 70local_fields (django_sorcery.db.meta.model.model_info

attribute), 34local_remote_pairs

(django_sorcery.db.meta.relations.relation_infoattribute), 35

local_remote_pairs_for_identity_key(django_sorcery.db.meta.relations.relation_infoattribute), 35

log() (django_sorcery.db.profiler.SQLAlchemyProfilingMiddlewaremethod), 45

log_results (django_sorcery.db.profiler.SQLAlchemyProfilingMiddlewareattribute), 45

logger (django_sorcery.db.middleware.BaseMiddlewareattribute), 41

logger (django_sorcery.db.profiler.SQLAlchemyProfilingMiddlewareattribute), 45

lookup_app() (django_sorcery.management.alembic.AlembicCommandmethod), 62

lower() (in module django_sorcery.utils), 83

Mmake_args() (in module django_sorcery.utils), 83make_middleware()

(django_sorcery.db.sqlalchemy.SQLAlchemymethod), 51

make_url() (in module django_sorcery.db.url), 53make_url_from_settings() (in module

django_sorcery.db.url), 53makeprop() (in module

django_sorcery.db.sqlalchemy), 52ManyToMany() (django_sorcery.db.relations.RelationsMixin

method), 47ManyToOne() (django_sorcery.db.relations.RelationsMixin

method), 47mapper (django_sorcery.db.meta.model.model_info at-

tribute), 34mapping (django_sorcery.routers.Route attribute), 81max_digits (django_sorcery.db.meta.column.numeric_column_info

attribute), 32media (django_sorcery.forms.ModelForm attribute), 80merge() (django_sorcery.db.sqlalchemy.SQLAlchemy

method), 51message (django_sorcery.validators.base.ValidateCantRemove

attribute), 63

Index 99

Page 104: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

message (django_sorcery.validators.base.ValidateEmptyWhenattribute), 63

message (django_sorcery.validators.base.ValidateNotEmptyWhenattribute), 64

message (django_sorcery.validators.base.ValidateOnlyOneOfattribute), 64

message (django_sorcery.validators.base.ValidateTogetherModelFieldsattribute), 64

message (django_sorcery.validators.base.ValidateUniqueattribute), 65

message (django_sorcery.validators.base.ValidateValueattribute), 65

metadata_class (django_sorcery.db.sqlalchemy.SQLAlchemyattribute), 52

model (django_sorcery.db.meta.model.model_info at-tribute), 34

model (django_sorcery.formsets.base.BaseModelFormSetattribute), 55

model (django_sorcery.views.base.SQLAlchemyMixinattribute), 67

model_class (django_sorcery.db.meta.composite.composite_infoattribute), 33

model_class (django_sorcery.db.meta.model.model_infoattribute), 34

model_class (django_sorcery.db.sqlalchemy.SQLAlchemyattribute), 52

model_info (class in django_sorcery.db.meta.model),33

model_info_meta (class indjango_sorcery.db.meta.base), 29

model_name (django_sorcery.db.meta.model.model_infoattribute), 34

model_to_dict() (django_sorcery.forms.BaseModelFormmethod), 79

model_to_dict() (in module django_sorcery.forms),80

ModelChoiceField (class in django_sorcery.fields),78

ModelChoiceIterator (class indjango_sorcery.fields), 79

ModelForm (class in django_sorcery.forms), 80modelform_factory() (in module

django_sorcery.forms), 80ModelFormMetaclass (class in

django_sorcery.forms), 80ModelFormMixin (class in

django_sorcery.views.edit), 69ModelFormMixin (class in django_sorcery.viewsets),

72ModelFormMixin (class in

django_sorcery.viewsets.mixins), 76modelformset_factory() (in module

django_sorcery.formsets.base), 55ModelMultipleChoiceField (class in

django_sorcery.fields), 79ModelViewSet (class in django_sorcery.viewsets), 71ModelViewSet (class in

django_sorcery.viewsets.base), 74MultipleObjectMixin (class in

django_sorcery.views.list), 70MultipleObjectTemplateResponseMixin

(class in django_sorcery.views.list), 70

Nname (django_sorcery.db.meta.column.column_info at-

tribute), 30name (django_sorcery.db.meta.composite.composite_info

attribute), 33name (django_sorcery.db.meta.relations.relation_info

attribute), 35name (django_sorcery.db.query.Operation attribute), 45name (django_sorcery.management.alembic.AlembicAppConfig

attribute), 61name (django_sorcery.routers.DynamicRoute attribute),

81name (django_sorcery.routers.Route attribute), 81Namespace (class in django_sorcery.db.signals), 49namespace (django_sorcery.management.commands.sorcery.Command.Meta

attribute), 56NamespacedCommand (class in

django_sorcery.management.base), 62negated (django_sorcery.validators.base.ValidateValue

attribute), 65NestedValidationError, 77new (django_sorcery.db.sqlalchemy.SQLAlchemy at-

tribute), 52new() (django_sorcery.viewsets.CreateModelMixin

method), 72new() (django_sorcery.viewsets.mixins.CreateModelMixin

method), 75no_autoflush (django_sorcery.db.sqlalchemy.SQLAlchemy

attribute), 52null (django_sorcery.db.meta.column.column_info at-

tribute), 30NullBooleanField (class in

django_sorcery.db.fields), 39numeric_column_info (class in

django_sorcery.db.meta.column), 32

Oobject (django_sorcery.views.base.BaseSingleObjectMixin

attribute), 66object_name (django_sorcery.db.meta.model.model_info

attribute), 34object_session() (django_sorcery.db.sqlalchemy.SQLAlchemy

method), 52OneToMany() (django_sorcery.db.relations.RelationsMixin

method), 48

100 Index

Page 105: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

OneToOne() (django_sorcery.db.relations.RelationsMixinmethod), 48

Operation (class in django_sorcery.db.query), 45opts (django_sorcery.db.meta.model.model_info at-

tribute), 34order_by() (django_sorcery.db.query.Query method),

46ordering (django_sorcery.db.meta.model.model_info

attribute), 34ordering (django_sorcery.views.base.BaseMultipleObjectMixin

attribute), 66

Ppage_kwarg (django_sorcery.views.base.BaseMultipleObjectMixin

attribute), 66paginate_by (django_sorcery.views.base.BaseMultipleObjectMixin

attribute), 66paginate_orphans (django_sorcery.views.base.BaseMultipleObjectMixin

attribute), 66paginate_queryset()

(django_sorcery.views.base.BaseMultipleObjectMixinmethod), 66

paginator_class (django_sorcery.views.base.BaseMultipleObjectMixinattribute), 66

parameters (django_sorcery.db.profiler.Query at-tribute), 44

parent (django_sorcery.db.meta.column.column_infoattribute), 30

parent (django_sorcery.db.meta.composite.composite_infoattribute), 33

parent_mapper (django_sorcery.db.meta.relations.relation_infoattribute), 35

parent_model (django_sorcery.db.meta.column.column_infoattribute), 30

parent_model (django_sorcery.db.meta.composite.composite_infoattribute), 33

parent_model (django_sorcery.db.meta.relations.relation_infoattribute), 35

parent_table (django_sorcery.db.meta.relations.relation_infoattribute), 35

perform_destoy() (django_sorcery.viewsets.DeleteModelMixinmethod), 72

perform_destoy() (django_sorcery.viewsets.mixins.DeleteModelMixinmethod), 76

post() (django_sorcery.views.edit.BaseCreateViewmethod), 68

post() (django_sorcery.views.edit.BaseUpdateViewmethod), 68

post() (django_sorcery.views.edit.DeletionMixinmethod), 69

post() (django_sorcery.views.edit.ProcessFormViewmethod), 69

prepare() (django_sorcery.db.sqlalchemy.SQLAlchemymethod), 52

prepare_instance_value()(django_sorcery.fields.ModelChoiceFieldmethod), 78

prepare_value() (django_sorcery.fields.EnumFieldmethod), 78

prepare_value() (django_sorcery.fields.ModelChoiceFieldmethod), 78

prepare_value() (django_sorcery.fields.ModelMultipleChoiceFieldmethod), 79

primary_keys (django_sorcery.db.meta.model.model_infoattribute), 34

primary_keys_from_dict()(django_sorcery.db.meta.model.model_infomethod), 34

primary_keys_from_instance()(django_sorcery.db.meta.model.model_infomethod), 34

print_help() (django_sorcery.management.base.NamespacedCommandmethod), 62

print_history() (django_sorcery.management.commands.sorcery_history.Historymethod), 59

private_fields (django_sorcery.db.meta.model.model_infoattribute), 35

process_form() (django_sorcery.viewsets.mixins.ModelFormMixinmethod), 76

process_form() (django_sorcery.viewsets.ModelFormMixinmethod), 73

process_request()(django_sorcery.db.middleware.BaseMiddlewaremethod), 41

process_request()(django_sorcery.db.profiler.SQLAlchemyProfilingMiddlewaremethod), 45

process_response()(django_sorcery.db.middleware.BaseMiddlewaremethod), 41

process_response()(django_sorcery.db.profiler.SQLAlchemyProfilingMiddlewaremethod), 45

process_revision_directives() (in moduledjango_sorcery.db.alembic.signals), 29

ProcessFormView (class indjango_sorcery.views.edit), 69

prop (django_sorcery.db.meta.composite.composite_infoattribute), 33

properties (django_sorcery.db.meta.composite.composite_infoattribute), 33

properties (django_sorcery.db.meta.model.model_infoattribute), 35

property (django_sorcery.db.meta.column.column_infoattribute), 30

put() (django_sorcery.views.edit.ProcessFormViewmethod), 69

Index 101

Page 106: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

Qqueries (django_sorcery.db.profiler.SQLAlchemyProfiler

attribute), 44Query (class in django_sorcery.db.profiler), 44Query (class in django_sorcery.db.query), 45query() (django_sorcery.db.session.SignallingSession

method), 48query() (django_sorcery.db.sqlalchemy.SQLAlchemy

method), 52query_class (django_sorcery.db.sqlalchemy.SQLAlchemy

attribute), 52query_options (django_sorcery.views.base.SQLAlchemyMixin

attribute), 67query_pkg_and_slug

(django_sorcery.views.base.BaseSingleObjectMixinattribute), 66

QueryProperty (class in django_sorcery.db.query),46

queryproperty() (django_sorcery.db.sqlalchemy.SQLAlchemymethod), 52

queryset (django_sorcery.fields.ModelChoiceField at-tribute), 78

queryset (django_sorcery.views.base.SQLAlchemyMixinattribute), 67

RReadOnlyModelViewSet (class in

django_sorcery.viewsets), 71ReadOnlyModelViewSet (class in

django_sorcery.viewsets.base), 74receivers (django_sorcery.db.signals.ScopedSignal

attribute), 49record_models() (in module

django_sorcery.db.session), 48refresh() (django_sorcery.db.sqlalchemy.SQLAlchemy

method), 52register() (django_sorcery.routers.BaseRouter

method), 81registry (django_sorcery.db.sqlalchemy.SQLAlchemy

attribute), 52registry_class (django_sorcery.db.sqlalchemy.SQLAlchemy

attribute), 52related_mapper (django_sorcery.db.meta.relations.relation_info

attribute), 35related_model (django_sorcery.db.meta.relations.relation_info

attribute), 35related_table (django_sorcery.db.meta.relations.relation_info

attribute), 35relation_info (class in

django_sorcery.db.meta.relations), 35relationship (django_sorcery.db.meta.relations.relation_info

attribute), 35relationships (django_sorcery.db.meta.model.model_info

attribute), 35

RelationsMixin (class indjango_sorcery.db.relations), 47

remove() (django_sorcery.db.middleware.SQLAlchemyDBMiddlewaremethod), 41

remove() (django_sorcery.db.sqlalchemy.SQLAlchemymethod), 52

remove() (django_sorcery.db.utils.dbdict method), 54required (django_sorcery.db.meta.column.column_info

attribute), 30retrieve() (django_sorcery.viewsets.mixins.RetrieveModelMixin

method), 77retrieve() (django_sorcery.viewsets.RetrieveModelMixin

method), 73RetrieveModelMixin (class in

django_sorcery.viewsets), 73RetrieveModelMixin (class in

django_sorcery.viewsets.mixins), 76return_response()

(django_sorcery.db.middleware.BaseMiddlewaremethod), 41

Revision (class in django_sorcery.management.commands.sorcery_revision),60

revision (django_sorcery.management.commands.sorcery.Commandattribute), 57

rollback() (django_sorcery.db.middleware.SQLAlchemyDBMiddlewaremethod), 41

rollback() (django_sorcery.db.sqlalchemy.SQLAlchemymethod), 52

rollback() (django_sorcery.db.utils.dbdict method),54

Route (class in django_sorcery.routers), 81routes (django_sorcery.routers.SimpleRouter at-

tribute), 82run_command_from_argv()

(django_sorcery.management.base.NamespacedCommandmethod), 62

run_env() (django_sorcery.management.alembic.AlembicCommandmethod), 62

run_from_argv() (django_sorcery.management.base.NamespacedCommandmethod), 62

run_migrations_offline()(django_sorcery.management.alembic.AlembicCommandmethod), 62

run_migrations_online()(django_sorcery.management.alembic.AlembicCommandmethod), 62

run_validators() (django_sorcery.db.meta.column.column_infomethod), 30

run_validators() (django_sorcery.db.meta.composite.composite_infomethod), 33

run_validators() (django_sorcery.db.meta.model.model_infomethod), 35

run_validators() (django_sorcery.db.mixins.CleanMixinmethod), 42

102 Index

Page 107: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

Ssa_state() (django_sorcery.db.meta.model.model_info

method), 35sanitize_separators() (in module

django_sorcery.utils), 83save() (django_sorcery.forms.BaseModelForm

method), 79save() (django_sorcery.formsets.base.BaseModelFormSet

method), 55save() (django_sorcery.formsets.inline.BaseInlineFormSet

method), 55save_instance() (django_sorcery.forms.BaseModelForm

method), 79scalar() (django_sorcery.db.sqlalchemy.SQLAlchemy

method), 52scalars() (django_sorcery.db.sqlalchemy.SQLAlchemy

method), 52scoped_signals (django_sorcery.db.signals.Namespace

attribute), 49ScopedSignal (class in django_sorcery.db.signals),

49scopedsignal() (django_sorcery.db.signals.Namespace

method), 49script (django_sorcery.management.alembic.AlembicAppConfig

attribute), 61serialize() (in module django_sorcery.db.models),

44session (django_sorcery.formsets.base.BaseModelFormSet

attribute), 55session (django_sorcery.views.base.SQLAlchemyMixin

attribute), 67session() (django_sorcery.db.sqlalchemy.SQLAlchemy

method), 52session_class (django_sorcery.db.sqlalchemy.SQLAlchemy

attribute), 52session_factory (django_sorcery.db.sqlalchemy.SQLAlchemy

attribute), 52setdefaultattr() (in module django_sorcery.utils),

84setup_config() (in module

django_sorcery.db.alembic.base), 29ShowHeads (class in

django_sorcery.management.commands.sorcery_heads),59

SignallingSession (class indjango_sorcery.db.session), 48

simple_repr() (in moduledjango_sorcery.db.models), 44

SimpleRouter (class in django_sorcery.routers), 81SingleObjectMixin (class in

django_sorcery.views.detail), 67SingleObjectTemplateResponseMixin (class

in django_sorcery.views.detail), 67slug_field (django_sorcery.views.base.BaseSingleObjectMixin

attribute), 66slug_url_kwarg (django_sorcery.views.base.BaseSingleObjectMixin

attribute), 66SlugField (class in django_sorcery.db.fields), 39SmallIntegerField (class in

django_sorcery.db.fields), 40sorcery_apps (django_sorcery.management.alembic.AlembicCommand

attribute), 62SQLAlchemy (class in django_sorcery.db.sqlalchemy),

49SQLAlchemy.BaseComposite (class in

django_sorcery.db.sqlalchemy), 49SQLAlchemy.CompositeField (class in

django_sorcery.db.sqlalchemy), 50sqlalchemy_profiler() (in module

django_sorcery.pytest_plugin), 80SQLAlchemyDBMiddleware (class in

django_sorcery.db.middleware), 41SQLAlchemyMiddleware (class in

django_sorcery.db.middleware), 41SQLAlchemyMixin (class in

django_sorcery.views.base), 66SQLAlchemyProfiler (class in

django_sorcery.db.profiler), 44SQLAlchemyProfilingMiddleware (class in

django_sorcery.db.profiler), 45SQLAModelFormOptions (class in

django_sorcery.forms), 80Stamp (class in django_sorcery.management.commands.sorcery_stamp),

60stamp (django_sorcery.management.commands.sorcery.Command

attribute), 57stamp() (django_sorcery.management.commands.sorcery_stamp.Stamp

method), 60start() (django_sorcery.db.profiler.SQLAlchemyProfiler

method), 44start() (django_sorcery.db.profiler.SQLAlchemyProfilingMiddleware

method), 45start() (django_sorcery.testing.Transact method), 83statement (django_sorcery.db.profiler.Query at-

tribute), 44stats (django_sorcery.db.profiler.SQLAlchemyProfiler

attribute), 45stop() (django_sorcery.db.profiler.SQLAlchemyProfiler

method), 45stop() (django_sorcery.testing.Transact method), 83string() (in module django_sorcery.db.url), 53string_column_info (class in

django_sorcery.db.meta.column), 32string_list() (in module django_sorcery.db.url),

54success_url (django_sorcery.views.edit.DeletionMixin

attribute), 69success_url (django_sorcery.viewsets.mixins.ModelFormMixin

Index 103

Page 108: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

attribute), 76success_url (django_sorcery.viewsets.ModelFormMixin

attribute), 73

TTable() (django_sorcery.db.sqlalchemy.SQLAlchemy

method), 50tables (django_sorcery.management.alembic.AlembicAppConfig

attribute), 61template_name_field

(django_sorcery.views.detail.SingleObjectTemplateResponseMixinattribute), 68

template_name_suffix(django_sorcery.views.detail.SingleObjectTemplateResponseMixinattribute), 68

template_name_suffix(django_sorcery.views.edit.CreateView at-tribute), 68

template_name_suffix(django_sorcery.views.edit.DeleteView at-tribute), 69

template_name_suffix(django_sorcery.views.edit.UpdateView at-tribute), 70

template_name_suffix(django_sorcery.views.list.MultipleObjectTemplateResponseMixinattribute), 70

text_column_info (class indjango_sorcery.db.meta.column), 32

TextField (class in django_sorcery.db.fields), 40time_column_info (class in

django_sorcery.db.meta.column), 32TimeField (class in django_sorcery.db.fields), 40timestamp (django_sorcery.db.profiler.Query at-

tribute), 44TimestampField (class in django_sorcery.db.fields),

40to_python() (django_sorcery.db.meta.column.boolean_column_info

method), 29to_python() (django_sorcery.db.meta.column.choice_column_info

method), 30to_python() (django_sorcery.db.meta.column.column_info

method), 30to_python() (django_sorcery.db.meta.column.date_column_info

method), 31to_python() (django_sorcery.db.meta.column.datetime_column_info

method), 31to_python() (django_sorcery.db.meta.column.enum_column_info

method), 31to_python() (django_sorcery.db.meta.column.float_column_info

method), 31to_python() (django_sorcery.db.meta.column.integer_column_info

method), 32

to_python() (django_sorcery.db.meta.column.interval_column_infomethod), 32

to_python() (django_sorcery.db.meta.column.numeric_column_infomethod), 32

to_python() (django_sorcery.db.meta.column.string_column_infomethod), 32

to_python() (django_sorcery.db.meta.column.time_column_infomethod), 32

to_python() (django_sorcery.fields.EnumFieldmethod), 78

to_python() (django_sorcery.fields.ModelChoiceFieldmethod), 78

to_python() (django_sorcery.fields.ModelMultipleChoiceFieldmethod), 79

Transact (class in django_sorcery.testing), 83transact() (in module

django_sorcery.pytest_plugin), 80transaction (django_sorcery.db.sqlalchemy.SQLAlchemy

attribute), 52TransactionContext (class in

django_sorcery.db.transaction), 52twophase (django_sorcery.db.sqlalchemy.SQLAlchemy

attribute), 52type_class (django_sorcery.db.fields.BigIntegerField

attribute), 37type_class (django_sorcery.db.fields.BinaryField at-

tribute), 37type_class (django_sorcery.db.fields.BooleanField

attribute), 37type_class (django_sorcery.db.fields.CharField at-

tribute), 37type_class (django_sorcery.db.fields.DateField at-

tribute), 37type_class (django_sorcery.db.fields.DateTimeField

attribute), 38type_class (django_sorcery.db.fields.DecimalField

attribute), 38type_class (django_sorcery.db.fields.DurationField

attribute), 38type_class (django_sorcery.db.fields.EnumField at-

tribute), 38type_class (django_sorcery.db.fields.Field attribute),

39type_class (django_sorcery.db.fields.FloatField at-

tribute), 39type_class (django_sorcery.db.fields.IntegerField at-

tribute), 39type_class (django_sorcery.db.fields.SmallIntegerField

attribute), 40type_class (django_sorcery.db.fields.TextField

attribute), 40type_class (django_sorcery.db.fields.TimeField at-

tribute), 40type_class (django_sorcery.db.fields.TimestampField

104 Index

Page 109: Django Sorcery Documentation

Django Sorcery Documentation, Release 0.11.3

attribute), 40

Uunhook() (django_sorcery.testing.Transact method),

83unique (django_sorcery.db.meta.column.column_info

attribute), 31unique_fields (django_sorcery.formsets.base.BaseModelFormSet

attribute), 55unique_together (django_sorcery.db.meta.model.model_info

attribute), 35update() (django_sorcery.db.utils.dbdict method), 54update() (django_sorcery.viewsets.mixins.UpdateModelMixin

method), 77update() (django_sorcery.viewsets.UpdateModelMixin

method), 74update_attribute()

(django_sorcery.forms.BaseModelFormmethod), 79

update_error_dict()(django_sorcery.exceptions.NestedValidationErrormethod), 77

UpdateModelMixin (class indjango_sorcery.viewsets), 73

UpdateModelMixin (class indjango_sorcery.viewsets.mixins), 77

UpdateView (class in django_sorcery.views.edit), 69Upgrade (class in django_sorcery.management.commands.sorcery_upgrade),

60upgrade (django_sorcery.management.commands.sorcery.Command

attribute), 57upgrade() (django_sorcery.management.commands.sorcery_upgrade.Upgrade

method), 61url (django_sorcery.routers.DynamicRoute attribute),

81url (django_sorcery.routers.Route attribute), 81URLField (class in django_sorcery.db.fields), 40urls (django_sorcery.routers.BaseRouter attribute), 81uselist (django_sorcery.db.meta.relations.relation_info

attribute), 35

Vvalid_value() (django_sorcery.fields.EnumField

method), 78validate() (django_sorcery.db.meta.column.column_info

method), 31validate() (django_sorcery.fields.ModelChoiceField

method), 79ValidateCantRemove (class in

django_sorcery.validators.base), 62ValidateEmptyWhen (class in

django_sorcery.validators.base), 63ValidateNotEmptyWhen (class in

django_sorcery.validators.base), 63

ValidateOnlyOneOf (class indjango_sorcery.validators.base), 64

ValidateTogetherModelFields (class indjango_sorcery.validators.base), 64

ValidateUnique (class indjango_sorcery.validators.base), 64

ValidateValue (class indjango_sorcery.validators.base), 65

ValidationRunner (class indjango_sorcery.validators.runner), 65

validators (django_sorcery.db.meta.column.column_infoattribute), 31

verbose_name (django_sorcery.db.meta.model.model_infoattribute), 35

verbose_name_plural(django_sorcery.db.meta.model.model_infoattribute), 35

version_path (django_sorcery.management.alembic.AlembicAppConfigattribute), 61

Wwidget (django_sorcery.db.meta.column.column_info

attribute), 31widget (django_sorcery.fields.ModelMultipleChoiceField

attribute), 79widget_class (django_sorcery.db.fields.Field at-

tribute), 39widget_class (django_sorcery.db.fields.TextField at-

tribute), 40

Index 105