Jan 29 2009

Django ORM now supports fields references in filters

Category: Djangovbmendes @ 08:28

Today was added a new feature to django ORM. Now it supports references to fields in filters expressions. Just checkout the SVN version and enjoy it.

Before this update, queryset could be filtered only by absolute values.

queryset.filter(field='absolute value')

Will generate somthing like this:

SELECT * FROM table_name WHERE field = 'absolute value';

Now you can filter by another’s table field value.

queryset.filter(field=F('another_field'))

Will generate something like this:

SELECT * FROM table_name WHERE field = another_field;

The feature also supports arithmetical operations in the lookups so you can do filters where the views_number is twice as big as the comments_number.

queryset.filter(views_number__gt=F('comments_number')*2)

Will generate a SQL like this:

SELECT * FROM table_name WHERE views_number = comments_number*2;

It’s a very good feature. So, checkout the SVN version and take a look at docs/topics/db/queries.txt to know more about this.

Tags: , ,


Jan 19 2009

External apps i18n in Django

Category: Djangovbmendes @ 12:59

Django has the good feature of internationalization. It’s very simple to use that it generates the .po files automatically from your project. All you have to do is complete the .po file with the translated text. To create these files, all you have to do is create a folder in your project called locale and run the command ./manage.py makemessages -l <your-locale>. That’s very easy, but I realized that it don’t get the string inside your external apps. So, after some search in internet, i found a way to get this file with the app’s strings. And, as all in django must be, it is a pluggable way to solve the problem.

All you have to do is create a folder named locale inside your app’s folder and run the command django-admin.py makemessages -l <your-locale> and it will create the file for you. To compile the messages, use the command django-admin.py compilemessages -l <your-locale>

That’s it, as simple as everything in django.

Tags: , , ,


Jan 15 2009

Django Aggregation Released

Category: Django, Pythonvbmendes @ 11:57

The aggregation is already available in Django SVN version. Now, it’s possible to do things such count authors of all book entries, count comments os all post entries, sum values of all sales to a client and much more.

Here is the official documentation of this feature: http://docs.djangoproject.com/en/dev/topics/db/aggregation/

Tags: , ,


Dec 19 2008

Builtin template tags and filters in Django

Category: Django, Pythonvbmendes @ 12:11

A good feature of Django Framework is the template tags and template filters. But it sucks when you have to load the filters in each template like this:

{% load mytemplatetags %}

It was much better if you just use the filters, without the need to load it. The reason you have to load is to achieve a better performance. But there’s a function of the template module called add_to_builtins that solves this problem. You can easily define a template tag or filter as builtin and use it like the builtin django template tags and filters. Just put this code in a file that is loaded ever, like the init.py of your project.

from django.template import add_to_builtins
add_to_builtins('path.to.templatetags.file')

Where ‘path.to.templatetags.file’ is the path of the file containing the template tags. For example, I have an app, inside my project, named mytagsapp. Inside this app I have the module templatetags with a file named mytags.py with my custom tags. So I will have to call add_builtins(‘mytagsapp.templatetags.mytags’). My project folder should look like this:

Folders structure

Folders structure

Make sure your app is in the INSTALED_APPS setting in your settings.py project. It will guarantee that the init.py of you app will get called. So just put the code above in this file (red in image).

Remember to not use this feature with all your template filters as it will mean loss of performance.

Tags: , , , ,


Dec 15 2008

Removing Empty Labels from forms.ChoiceField in ModelFormSets

Category: Django, Pythonvbmendes @ 21:52

When you use a Model Choice Field in Django, it automatically creates an empty option in the generated select widget. But in some special cases, you don’t want this empty option to be there. So I decided to find the way to remove it. It’s much more simple then you think. Just create your model declaring the model choice field like this:

fieldname = forms.ModelChoiceField(queryset=RelationModel.objects,empty_label=None)

It’s simple like that. Just set the empty_label argument to None. But whe using ModelFormSets, there is a little more work to do. You have to create a new BaseModelFormSet like this:

from django.forms.models import BaseModelFormSet</p>

<p>class MyBaseModelFormSet(BaseModelFormSet):
    def add_fields(self, form, index):
        super(MyBaseModelFormSet,self).add_fields(form,index)
        form.fields['fieldname'] = forms.ModelChoiceField(queryset=RelationModel.objects,empty_label=None)

Pay atention that you have to override the add_fields method and change your field in the form fields array. Finally you have to pass this BaseModelFormSet as argument to the modelformset_factory:

from django.forms.models import modelformset_factory</p>

<p>MyModelFormset = modelformset_factory(MyModel,formset=MyBaseModelFormSet)

Tags: , ,


Jul 29 2008

Django Graphviz – Documentando seus models

Category: Djangovbmendes @ 13:03

Navegando pelos blogs hoje eu me deparei com uma ferramenta muito interessante: o Django Graphviz. Ele gera, a partir do arquivo models.py, uma representação gráfica do banco de dados da aplicação. Segue abaixo uma imagem gerada por ela:

Representação gráfica do banco de dados

No blog do Mayron Cachina [1] existe um tutorial explicando como utilizar a ferramenta.

[1] http://cachina.wordpress.com/2008/02/29/djangographviz-cria-um-png-de-seu-model/


« Previous Page