Git Product home page Git Product logo

django-queryset-cheatsheet's Introduction

Cheatsheet for Django QuerySets

Current Django Version: 3.0

Methods that return new QuerySets

Dajngo uses MVC system : Model - View - Controllers

Creatin a Django Project:

python -m venv venv create a virtual encironment

source venv/bin/activate activate virtual environment venv

pip install -r requirements.txt install all the required tools

0. Create Database:

createdb db_name

1. Start a Project:

django-admin startproject <name> . This makes sure that the project is not nested

mysite/            --> A container for your project/ can be renamed.   

manage.py       --> A command-line utility that lets you interact with this Django project. 

mysite/.        --> Actual Python package for your project     

    __init__.py --> An empty file that tells Python that this directory should be considered a Python package.   
    
    settings.py --> Settings/configuration for this Django project.       
    
    urls.py.    --> The URL declarations for this Django project; a “table of contents” of your Django-powered site.  
    
    asgi.py     --> An entry-point for ASGI-compatible web servers to serve your project.   
    
    wsgi.py     --> An entry-point for WSGI-compatible web servers to serve your project.`  

2. Verify Django project works. Change into the outer mysite directory

python manage.py runserver

Starting development server at http://127.0.0.1:8000/

Quit the server with CONTROL-C.

Changing the port from the default development server on the internal IP at port 8000.

python manage.py runserver 8080

Changing the server’s IP, pass it along with the port.

python manage.py runserver 0:8000

3. Create your app, make sure you’re in the same directory as manage.py , use:

python manage.py startapp name

4. Make. migration

The migrate command looks at the INSTALLED_APPS setting and creates any necessary database tables according to the database settings in your project/settings.py file and the database migrations shipped with the app (Next migrations will completed after the models are ceated, look at #7).

python manage.py migrate

python manage.py createsuperuser

13. In our app, create models:

Models are Python objects that define the structure of an application's data, and provide mechanisms to manage (add, modify, delete) and query records in the database. Here, each model is represented by a class that subclasses django.db.models.Model. Each model has a number of class variables, each of which represents a database field in the model.

App/models.py

from django.db import models

class Question(models.Model):

    question_text = models.CharField(max_length=200)
  
    pub_date = models.DateTimeField('date published')

14 Activate models

The model code gives Django a lot of information. With it, Django is able to: a. Create a database schema (CREATE TABLE statements) for this app. b. Create a Python database-access API for accessing Question and Choice objects. after telling the project that the app is installed in the project INSTALLED_APPS section in settings.

python manage.py makemigrations <app_name>, then run

python manage.py migrate <app_name>

6. Views:

A view is a request handler function, which receives HTTP requests and returns HTTP responses. Views access the data needed to satisfy requests via models, and delegate the formatting of the response to templates. from django.http import HttpResponse

def index(request):

`return HttpResponse()`

7. URLs for App:

While it is possible to process requests from every single URL via a single function, it is much more maintainable to write a separate view function to handle each resource. A URL mapper is used to redirect HTTP requests to the appropriate view based on the request URL. The URL mapper can also match particular patterns of strings or digits that appear in a URL and pass these to a view function as data.

from django.urls import path

 from . import views

    urlpatterns = [

    path('', views.index, name='index'),

    ]

8. URLs for project.

When Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing. URLconf is like a table of contents for your Django-powered Web site.

 from django.contrib import admin

 from django.urls import include, path

 urlpatterns = [

  path('polls/', include('polls.urls')),

  path('admin/', admin.site.urls),

 ]

9. A index view is now wiredinto the URLconf. Verify it’s working with:

python manage.py runserver

10. Completing Setup In project/settings.py

Add Installed_apps

Add'APP_name', 'django_extensions' under INSTALLED_APPS 

Add Database:

If you are not using SQLite as your database, additional settings such as USER, PASSWORD, and HOST

`DATABASES = {

    'default': {

        'ENGINE': 'django.db.backends.postgresql',

        'NAME': 'mydatabase'
    }
}`

15 Playing with the API/Python shell

Now, let’s hop into the interactive Python shell and play around with the free API Django gives you. To invoke the Python shell, use this command:

python manage.py shell_plus

16 str() AND Model.str()

It’s important to add str() methods to your models, not only for your own convenience when dealing with the interactive prompt, but also because objects’ representations are used throughout Django’s automatically-generated admin.

class Choice(models.Model):

    # ...

def __str__(self):

    return self.choice_text

settings.py

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

Templates:

A template is a text file defining the structure or layout of a file (such as an HTML page), with placeholders used to represent actual content. A view can dynamically create an HTML page using an HTML template, populating it with data from a model. A template can be used to define the structure of any type of file; it doesn't have to be HTML!

Other commands:

  1. Create Database
  2. Set up your models
  3. Run makemigrations `
  4. Run python manage.py migrate
  5. If you make alterations to models, rerun the migrations commands to update db.
  6. Tests to pass: python manage.py test --failfest

python manage.py shell_plus to complete commands in the py shell

python -m venv venv create a virtual encironment

source venv/bin/activate activate virtual environment venv

pip install -r requirements.txt install all the

django-admin.py startproject <project_name> start a new Django project

git init Initialize new Git repo

git add -A add your changes to staging and then to the local repo.

git commit -am initial commit

git remote add origin PUSH your files to central repo.

git remote add origin github.com/Carole-Ouedraogo/new_repo

git push -u origin master

createdb <db_name>

python3 manage.py test

python3 manage.py migrate

python3 manage.py makemigrations <app_name>

python manage.py test --failfest test file is run

new_var = _ assigns, and gives you access to previous output in python shell

ON DELETE CASCADE delete child when parent is deleted

ON DELETE SET NULL set null when parent is deleted


Django APIs

Can be chained:

Entry.objects.filter(**kwargs).exclude(**kwargs).order_by(**kwargs)

Operators that return new QuerySets

Methods that do not return QuerySets

Field lookups

Field lookups are how you specify the meat of an SQL WHERE clause. They’re specified as keyword arguments to the QuerySet methods filter(), exclude() and get().

Example: Entry.objects.get(id__exact=14)  # note double underscore.

Protip: Use in to avoid chaining filter() and exclude()

Entry.objects.filter(status__in=['Hung over', 'Sober', 'Drunk'])

Aggregation functions (link)

Query-related tools (link)


Creative Commons License
Django-QuerySet-Cheatsheet by @chrisdl and @briandant is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

The contributors are as gods among ants and shall forever be remembered as such.

The Django web framework referenced in the Django-QuerySet-Cheatsheet is ​© 2005-2018 Django Software Foundation. Django is a registered trademark of the Django Software Foundation.

django-queryset-cheatsheet's People

Contributors

akshaysharma096 avatar bay007 avatar carole-ouedraogo avatar chrisdl avatar davidegalletti avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.