Lloeki
Lloeki

Reputation: 6713

How do Django queries 'cast' argument strings into the appropriate field-matching types?

Let's take the Django tutorial. In the first part we can find this model:

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

with which Django generates the following SQL:

CREATE TABLE "polls_poll" (
    "id" serial NOT NULL PRIMARY KEY,
    "question" varchar(200) NOT NULL,
    "pub_date" timestamp with time zone NOT NULL
);

One can note that Django automatically added an AutoField, gloriously named id, which is akin to an IntegerField in that it handles integers.

On part 3, we build a custom view, reachable through the following url pattern:

(r'^polls/(?P<poll_id>\d+)/$', 'polls.views.detail'),

The tutorial helpfully explains that a subsequent HTTP request will result in the following call:

detail(request=<HttpRequest object>, poll_id='23')

A few scrolls later, we can find this snippet:

def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)

Notice how the URL tail component becomes the poll_id argument with a string value of '23', happily churned by the Manager (and therefore QuerySet) get method to produce the result of an SQL query containing a WHERE clause with an integer value of 23 certainly looking like that one:

SELECT * FROM polls_poll WHERE id=23

Certainly Django performed the conversion from the fact that the id field is an AutoField one. The question is how, and when. Specifically, I want to know which internal methods are called, and in what order (kind of like what the doc explains for form validation).

Note: I took a look at sources in django.db.models and found a few *prep* methods, but don't know neither when or where they are called, let alone if they're what I'm looking for.

PS: I know it's not casting stricto sensu, but I think you get the idea.

Upvotes: 2

Views: 1373

Answers (1)

manji
manji

Reputation: 47978

I think it's in django.db.models.query.get_where_clause

Upvotes: 1

Related Questions