Rencontres Django a.k.a #djangocong
14 avril 2012
>>> from django.db import connection # DEBUG = True
>>> connection.queries
>>> connection.queries = [] # reset
import logging
l = logging.getLogger('django.db.backends')
l.setLevel(logging.DEBUG)
l.addHandler(logging.StreamHandler())
log_statement all >> /etc/postgresql/postgresql.conf [mysqld] log=/tmp/mysql.log >> /etc/mysql/my.cnf
class Car(models.Model):
is_locked = models.BooleanField(default=False)
paired_with = models.ForeignKey(RfidCard, related_name='paired_cars')
...
class CarTelemetry(models.Model):
car = models.ForeignKey(Car, related_name='telemetry_set') # many-to-one
time = LocalDateTimeField(default=datetime.datetime.now)
...
Pour chaque Car, récupèrer la carte RFID associée
<ul>
{% for car in cars %}
<li>{{ car.paired_with.get_kind_display }} : IT'S OVER 9000!!!!!!</li>
{% endfor %}
</ul>
Shortcut :
get_object_or_404(MyModel.objects.select_related(), field=value)
Exemples :
cars = Car.objects.select_related('paired_with')
telemetries = CarTelemetry.objects.select_related('car__paired_with')
Pour chaque Car, récupèrer les n télémétries associées
<div>
{% for car in cars %}
<ul>
{% for telemetry in car.telemetry_set.all %}
<li>IT'S OVER 9000!!!!!!</li>
{% endfor %}
</ul>
{% endfor %}
</div>
Rappel du modèle :
class CarTelemetry(models.Model):
car = models.ForeignKey(Car, related_name='telemetry_set')
...
cars = Car.objects.filter(is_locked=False)
telemetries = CarTelemetry.objects.filter(car__is_locked=False)
telemetries_by_car = {}
for t in telemetries:
telemetries_by_car.setdefault(t.car.pk, []).append(t)
# {18: [<CarTelemetry: 2012-02-29 10:44:36>,
# <CarTelemetry: 2012-02-29 10:50:36>,
# <CarTelemetry: 2012-02-29 10:54:38>]}
for car in cars:
car.telemetries = telemetries_by_car.get(car.id)
cars = Car.objects.filter(
is_locked=False,
).prefetch_related(
'telemetry_set',
)
class CarTestCase(TestCase):
def test_its_under_9000(self):
with self.assertNumQueries(3):
response = self.client.get(reverse('cars'))
self.assertEqual(response.status_code, 200)
Table of Contents | t |
---|---|
Exposé | ESC |
Full screen slides | e |
Presenter View | p |
Source Files | s |
Slide Numbers | n |
Toggle screen blanking | b |
Show/hide slide context | c |
Notes | 2 |
Help | h |