Herramientas de usuario

Herramientas del sitio


wiki2:python:django:models

Diferencias

Muestra las diferencias entre dos versiones de la página.

Enlace a la vista de comparación

Ambos lados, revisión anterior Revisión previa
Próxima revisión
Revisión previa
wiki2:python:django:models [2019/01/31 07:42]
alfred [Clean migrations]
wiki2:python:django:models [2020/05/09 09:25] (actual)
Línea 1: Línea 1:
 ====== Django Models ====== ====== Django Models ======
 +===== Migrations =====
 +
 +<​code>​
 +$ python manage.py makemigrations <app>
 +</​code> ​
 +Will create migration files for all the apps if the ''​app''​ was not indicated.
 +
 +<​code>​
 +$ python manage.py migrate
 +</​code> ​
 +Will apply migrations to the configured DB.
 ===== Signals ===== ===== Signals =====
  
Línea 60: Línea 71:
  
 ===== Fields ===== ===== Fields =====
 +==== DateTime Field ====
 +The auto_now_add will set the timezone.now() only when the instance is created, and auto_now will update the field everytime the save method is called.
  
 +<code python>
 +class Invoice(models.Model):​
 +    description = models.CharField(max_length=255)
 +    status = models.CharField(max_length=10)
 +    vendor = models.ForeignKey(Vendor)
 +    created_at = models.DateTimeField(auto_now_add=True)
 +    updated_at = models.DateTimeField(auto_now=True)
 +</​code>​
 ==== Image Field ==== ==== Image Field ====
  
Línea 89: Línea 110:
 </​code>​ </​code>​
  
 +
 +==== Choice ====
 +<​code>​
 +from django.db import models
 +
 +class Person(models.Model):​
 +    SHIRT_SIZES = (
 +        ('​S',​ '​Small'​),​
 +        ('​M',​ '​Medium'​),​
 +        ('​L',​ '​Large'​),​
 +    )
 +    name = models.CharField(max_length=60)
 +    shirt_size = models.CharField(max_length=2,​ choices=SHIRT_SIZES)
 +</​code>​
 +Get its values
 +<​code>​
 +>>>​ p = Person(name="​Fred Flintstone",​ shirt_size="​L"​)
 +>>>​ p.save()
 +>>>​ p.shirt_size
 +'​L'​
 +>>>​ p.get_shirt_size_display()
 +'​Large'​
 +</​code>​
 ==== Special fields ==== ==== Special fields ====
  
Línea 114: Línea 158:
  
 ===== How to... ===== ===== How to... =====
 +==== Deal with performed queries ====
 +See the current registered queries (with their times):
 +<​code>​
 +from django.db import connection
 +connection.queries
 +</​code>​
 +
 +See a concrete database queries:
 +<​code>​
 +from django.db import connections
 +connections['​my_db_alias'​].queries
 +</​code>​
 +
 +Delete the query array:
 +<​code>​
 +from django.db import reset_queries
 +reset_queries()
 +</​code>​
 ==== Get an app model ==== ==== Get an app model ====
 <​code>​ <​code>​
wiki2/python/django/models.1548920575.txt.gz · Última modificación: 2020/05/09 09:24 (editor externo)