Z
Z
zelsky2015-04-15 07:38:29
Django
zelsky, 2015-04-15 07:38:29

Django extra parameter when querying (where)?

Practice trying to fix the reading of the documentation.
There is a view:

def alboms(request,cat_id):
  show_albums = Album.objects.all().filter(cat=cat_id)
  rando = Photo.objects.all().order_by('?')[: 1]
  categir = Categories.objects.all()
  context = {'albom': show_albums,'categor': categir,'thumb':rando}

  return render(request,'adst/albums.html',context)

I get a random photo from a table with a photo. You need to add the where parameter so that a random photo is obtained from only one album and not from the whole database. ps The code of models, views, and templates is attached. pp.ss In the album model there is a field with IntegerField where I thought to add the photo ID for the preview. But something somehow did not grow together. Models
rando = Photo.objects.all().order_by('?')[: 1]

from django.db import models
from django_attach.models import Attachment
from django.contrib.contenttypes.generic import GenericRelation
from django import forms

# Create your models here.

class Categories(models.Model):
  id_cat = models.AutoField(primary_key=True)
  Name_cat = models.CharField(max_length=15)
  def __unicode__(self):
    return self.Name_cat


class Album(models.Model):
  cat = models.ForeignKey(Categories)
  id_alb = models.AutoField(primary_key=True)
  Name_album = models.CharField(max_length=100)
  Text_f_album = models.CharField(max_length=200)
  Title_page = models.CharField(max_length=70)
  Title_photo = models.CharField(max_length=60)
  Alt_photo = models.CharField(max_length=80)
  id_photo_for_thumb = models.IntegerField()
  desctiption = models.CharField(max_length=1100)
  def __unicode__(self):
    return '%s %s %s' % (self.Name_album, self.cat,self.id_photo_for_thumb)

class Photo(models.Model):
  alb = models.ForeignKey(Album)
  Title_f_photo = models.CharField(max_length=80)
  Alt_f_photo = models.CharField(max_length=80)
  image = models.ImageField(upload_to='media',default='_5q16cjpxm.jpg')
  def __unicode__(self):
    return self.Title_f_photo

Views
from django.shortcuts import render
from django.http import HttpResponse

from django.db import models
from adst.models import Album
from adst.models import Categories
from adst.models import Photo
# Create your views here.
def index(request):
  categir = Categories.objects.all()
  context = {'categor': categir}  
  return render(request,'adst/base.html',context)

def gallary(request,alb_id):
  get_photos = Photo.objects.all().filter(alb=alb_id)
  categir = Categories.objects.all()
  show_albums = Album.objects.all().filter(id_alb=alb_id)
  context = {'phot':get_photos,'categor': categir,'alb_opis':show_albums}
  return render(request,'adst/galar.html',context)

def alboms(request,cat_id):
  show_albums = Album.objects.all().filter(cat=cat_id)
  
  rando = Photo.objects.all().order_by('?')[: 1]
  categir = Categories.objects.all()
  context = {'albom': show_albums,'categor': categir,'thumb':rando}

  return render(request,'adst/albums.html',context)

Template for displaying albums
{% extends "adst/base.html" %}
{% load static %} 
{% block meta_title %}{{ categor.Name_cat }}{% endblock meta_title %}
 {% block content %} 
<!-- Контент -->    
{% for albo in albom %}
        <div class="col-lg-3 col-md-3 col-sm-6 col-xs-12">
          <div class="thumbnail with-caption">
           <a href="{% url "Watch" albo.id_alb %}"> {% for ran in thumb %}<img src="{{  ran.image.url }}" alt="My image"/> {% endfor%}</a>
            <center>
              {{ albo.Text_f_album }} {{rand.image.url }}
            </center>
          </div>
        </div> 
        {% endfor %}
        </div>
      </div>
    </div>
{% endblock content %}

URLS
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles import *
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    # Examples:
    url(r'^$', 'adst.views.index', name='home'),
    # url(r'^blast/', 'adst.views.testes', name='blast'),
    url(r'^watch/(?P<alb_id>\d+)$', 'adst.views.gallary', name='Watch'),
    # url(r'^albums/', 'adst.views.tisc', name='Alb'),
     url(r'^category/(?P<cat_id>\d+)$',  'adst.views.alboms', name='Albom'), 
    # url(r'^blog/', include('blog.urls')),
    url(r'^admin/', include(admin.site.urls)),
 ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
Y
Yuri Shikanov, 2015-04-15
@dizballanze

To select a random photo from albums that are in a category with id = cat_id

def albums(request, cat_id):
  show_albums = Album.objects.all().filter(cat=cat_id)
  random = Photo.objects.filter(alb__cat_id=cat_id).order_by('?')[: 1]
  categir = Categories.objects.all()
  context = {'albom': show_albums,'categor': categir,'thumb':random}

  return render(request,' adst/albums.html',context)

Z
zelsky, 2015-04-15
@zelsky

Thank you. But now not much in another mistake. For one category , it takes a random photo from an album in the same category . Everything is ok if there is one album in the category, but if there are three albums in the category, then all 3 will have one and the same photo.
How can you get a parameter other than def albums(request, cat_id): from here,
like this is not possible ?

random = Photo.objects.filter(alb=show_albums.alb_id).order_by('?')[: 1]

S
some1else, 2015-04-16
@some1else

Either loop through all albums, or the following trick (does not work on all db backends, it definitely works in PostgreSQL):
As a result, we will get one random photo for each album from the category.
However, do not forget that order_by '?' can be a very expensive database operation

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question