Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access data from models in view in Django?

So I have a models file:

import datetime

from django.db import models

class Organization(models.Model):
    name           = models.CharField(max_length=128, unique=True);
    description    = models.TextField(blank=True);
    location       = models.CharField(max_length=256, blank=True);
    contact_email  = models.EmailField(max_length=128, unique=True);
    org_type       = models.ForeignKey('OrganizationType');
    created_at     = models.DateTimeField(editable=False);
    updated_at     = models.DateTimeField();

def save(self, *args, **kwargs):
    ''' On save, update timestamps '''
    datetime_now = datetime.datetime.now();

    # If there's no ID, it's new
    if not self.id:
        self.created_at = datetime_now;

    # Always update the modified at value
    self.modified_at = datetime_now;

    return super(User, self).save(*args, **kwargs);

class Meta:
    app_label = 'bc';

And a view file Organization.py:

from django.shortcuts import render, redirect
from django.contrib import auth
from django.core.context_processors import csrf

from BearClubs.bc.forms.user import UserSignUpForm
from BearClubs.bc.models.organization import Organization

def directory(request):
    first_50_clubs = [];

    # get 50 clubs here

return render(request, 'directory.html' {'clubs': first_50_clubs});

I am really new to Django so pardon me. How do I go about getting the first 50 clubs in the first_50_clubs in the Organization.py view file?

like image 653
user3371983 Avatar asked Mar 14 '14 03:03

user3371983


People also ask

How do I get QuerySet in Django?

You get a QuerySet by using your model's Manager . Each model has at least one Manager , and it's called objects by default. Access it directly via the model class, like so: >>> Blog.objects <django.db.models.manager.Manager object at ...> >>> b = Blog(name='Foo', tagline='Bar') >>> b.objects Traceback: ...


1 Answers

According to the documentation, you can just use list slicing:

Use a subset of Python’s array-slicing syntax to limit your QuerySet to a certain number of results. This is the equivalent of SQL’s LIMIT and OFFSET clauses.

def directory(request):
    first_50_clubs = Organization.objects.all()[:50]

    return render(request, 'directory.html' {'clubs': first_50_clubs})

Also, you don't need to put semi-colons at the end of code lines in python.

Hope that helps.

like image 162
alecxe Avatar answered Nov 06 '22 23:11

alecxe