A "slug" is a way of generating a valid URL, generally using data already obtained. For instance, a slug uses the title of an article to generate a URL. I advise to generate the slug by means of a function, given the title (or another piece of data), rather than setting it manually.
An example:
<title> The 46 Year Old Virgin </title>
<content> A silly comedy movie </content>
<slug> the-46-year-old-virgin </slug>
Now let's pretend that we have a Django model such as:
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField(max_length=1000)
slug = models.SlugField(max_length=40)
How would you reference this object with a URL and with a meaningful name? You could for instance use Article.id so the URL would look like this:
www.example.com/article/23
Or, you might want to reference the title like this:
www.example.com/article/The 46 Year Old Virgin
Since spaces aren't valid in URLs, they must be replaced by %20
, which results in:
www.example.com/article/The%2046%20Year%20Old%20Virgin
Both attempts are not resulting in very meaningful, easy-to-read URL. This is better:
www.example.com/article/the-46-year-old-virgin
In this example, the-46-year-old-virgin
is a slug: it is created from the title by down-casing all letters, and replacing spaces by hyphens -
.
Also see the URL of this very web page for another example.
You can use Q objects for this. They can be negated with the ~
operator and combined much like normal Python expressions:
from myapp.models import Entry
from django.db.models import Q
Entry.objects.filter(~Q(id=3))
will return all entries except the one(s) with 3
as their ID:
[<Entry: Entry object>, <Entry: Entry object>, <Entry: Entry object>, ...]
Best Answer
See this:
http://docs.djangoproject.com/en/dev/ref/models/querysets/#id4
You create a
select_related
query set to follow relationships and pre-fetch related rows.Normally, you don't waste much time doing this until you know that the individual fetches done automagically by the ORM are too slow.
When you simply name a related object field:
The ORM will do the of the related subTable row. lazily.
You can't easily fetch an entire table into memory. QuerySets are "lazy" and don't fetch rows until there's no possible excuse. Consider this.
Then you may not actually need all the objects in
MainTable
. The query set is ready to fetch them. It just doesn't actually fetch them all. That's why we don't generally do anything more thanx.subTable
and leave it to the ORM to fetch the row as needed.Once in a while you can prove that it's too slow. Then you can do
MainTable.objects.select_related()...
and force navigation to rows in other tables.