git crib

Install git (debian)

sudo apt-get install git-core

Workflow

Generate SSH keys


View: https://help.github.com/articles/generating-ssh-keys

Clone a project (svn checkout equivalent)

git clone https://github.com/username/projectname.git
Creates projectname directory and clones the project.

Add a file to the repository

git add filename

Show project status

git status

Commit to the local repository

git commit -a -m "change description"

Upload to the central repository

git push git@github.com:username/projectname.git
or (see user configuration),
git push

Discard all local changes including newly added files

git reset --hard

Discard options

f you want to revert changes made to your working copy, do this:
git checkout .
If you want to revert changes made to the index (i.e., that you have added), do this:
git reset
If you want to revert a change that you have committed, do this:
git revert ...
Taken from: http://stackoverflow.com/questions/1146973/how-to-revert-all-local-changes-in-a-git-managed-project-to-previous-state

Show differences


Update project, download changes (svn update equivalent)

git pull

Show diff between master and local repository

git diff


Branches


Make a new branch

git branch rama

Show branches

git branch

Go to the branch rama

git checkout rama

Merge with master

git branch master (goto the main branch)
git merge "rama" (merge rama with main)


User configuration


User

To automate the pulls:

View the reponame
git config -l

And then
sudo git config remote.origin.url https://{USERNAME}:{PASSWORD}@github.com/{USERNAME}/{REPONAME}.git

Find all *.pyc and remove from the repository

find . -name "*.pyc" -exec git rm -f {} \;

Ignore some types of files (global)

git config --global core.excludesfile ~/.gitignore_global

Edit ~/.gitignore_global and add patterns like *.pyc

Ignore some types of files (local)

At the local repository edit .gitignore and add patterns.

Chuleta de git

## Branques

Campos calculados en django

Las operaciones sobre los objetos model de django se mapean a SQL mediante el ORM (Object-relational mapping). Un problema que tiene el ORM de django es que no tiene soporte directo para los campos calculados, que son aquellos que se obtienen a partir de los valores de los campos del registro para cada registro.

Por ejemplo, tenemos unos movimientos en los que interviene cantidad, precio y comisión. ¿Qué sentido tiene guardar en la BD el campo importe si en realidad ya tenemos toda la información para calcularlo?.


class Movimiento(models.Model):
   cantidad=models.DecimalField()
   precio=models.DecimalField()
   comision=models.DecimalField()

¿Cómo calculamos entonces el importe?. Hay dos alternativas: Una usando una property de python en el propio objeto model y otra usando extra en el queryset. Veamos:

class Movimiento(models.Model):
   cantidad=models.DecimalField()
   precio=models.DecimalField()
   comision=models.DecimalField()

   def _get_importe(self):
      return self.cantidad*self.cambio*(1-self.comision)
   importe = property(_get_importe)

Y ahí tenemos el importe del movimiento via movimiento.importe

La otra solución es usar extra en el queryset para añadir "a mano" el campo en la consulta SQL, sería:

target=movimiento.objects.extra(select={
'importe': 'cantidad*cambio*(1-comision)',})
for f in target:
print f.importe

Entonces, ¿Cuál es el problema?. Pues que todo esto son soluciones "de mentirijilla" puesto que realmente el campo importe no existe como tal en el gestor de BD y no podemos hacer cosas como sumar todos los importes haciendo una agregación, así esto

total_importe=modelo.aggregate(Sum('importe'))

Nos genera un error diciendo que el campo importe no existe.

Sin duda, el soporte para campos calculados es uno de las mejoras del ORM que puede trabajarse.


Fuentes:
http://stackoverflow.com/questions/3690343/django-orm-equivalent-for-this-sql-calculated-field-derived-from-related-table

Localizar las plantillas

Si queremos que los importes monetarios de nuestras plantillas nos salgan (en España) así:

1.256,56 €

en vez de así:

1256.56 €

tenemos que localizar la plantilla y dejar que django haga el trabajo duro.

Para empezar, en settings.py indicamos que queremos usar la localización añadiendo:

DEFAULT_CHARSET='utf-8'
THOUSAND_SEPARATOR= '.'
DECIMAL_SEPARATOR = ','
NUMBER_GROUPING = 3
USE_THOUSAND_SEPARATOR = True
FIRST_DAY_OF_WEEK = 1
LANGUAGE_CODE = 'es-es'
USE_L10N = True


En la plantilla, cargamos l10n y activamos la localización así:

{% load l10n %}
{% localize on %}

blah, blah, blah...

{% endlocalize %}


Y de forma mágica los importes aparecerán correctamente formateados. Para controlar la cantidad de decimales diferentes del estándar también podemos usar el filtro floatformat:precision así:

{{ importe|floatformat:6 }}