Answer the question
In order to leave comments, you need to log in
Django ORM - explain on your fingers how this query to the database (PostgreSQL) should look like?
Dear Toasters (c. Battlestar Galactica), I'm slowly but surely moving to the "bright side", but django-photologue is on the way to enlightenment.
I am writing a django application (car rental service), using django-photologue to manage images. I don’t understand how to select one photo related to this gallery through a gallery attached via foreign_key. ( Need a Django ORM solution )
To clarify the situation, the following tables are available:
My car model:
class Car(models.Model):
manufacturer = models.ForeignKey(CarManufacturer, verbose_name='Araç markası')
.......
gallery = models.ForeignKey(Gallery, verbose_name='Resimler')
.......
available = models.BooleanField(verbose_name='Araç mevcut')
is_rented = models.BooleanField(verbose_name='Araç kiralanabilir mi')
add_to_main = models.BooleanField(verbose_name='Anasayfaya ekle')
under_maintance = models.BooleanField(verbose_name='Araç servis dışı mıdır')
...........
...........
class Gallery(models.Model):
...........
photos = SortedManyToManyField('Photo', related_name='galleries',
verbose_name=_('photos'), null=True, blank=True)
...........
class Photo(ImageModel):
title = models.CharField(_('title'), max_length=50, unique=True)
slug = models.SlugField(_('slug'), unique=True)
...........
def get_absolute_url(self):
return reverse('pl-photo', args=[self.slug])
...........
cursor = connection.cursor()
cursor.execute ('''SELECT DISTINCT ON (cars_car)
cars_car.id AS id,
cars_carmanufacturer.name AS manufacturer,
cars_carmodel.name AS model,
photologue_photo.image AS photo
FROM
cars_car,
photologue_photo,
photologue_gallery_photos,
cars_carmanufacturer,
cars_carmodel
WHERE
cars_car.available = True AND
cars_car.add_to_slider = True AND
cars_car.under_maintance = False AND
cars_car.gallery_id = photologue_gallery_photos.gallery_id AND
cars_car.manufacturer_id = cars_carmanufacturer.id AND
cars_car.model_id = cars_carmodel.id AND
photologue_gallery_photos.photo_id = photologue_photo.id''')
cars = cursor.fetchall()
Answer the question
In order to leave comments, you need to log in
The simplest solution is to add a field to the car with a clear indication of one single photo and put it down at the time the car is saved or the photo is saved to the gallery. Otherwise, you are left to chance, choosing a photo that turns up.
Well, if in the current configuration - try prefetch_related - it will make another fetch to the database, but I'm not sure if it will work on the current scheme.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question