Skip to content

Instantly share code, notes, and snippets.

@leongjinqwen
Last active January 1, 2024 07:06
Show Gist options
  • Save leongjinqwen/e81fb2d035c9bab36af96b535614b6a3 to your computer and use it in GitHub Desktop.
Save leongjinqwen/e81fb2d035c9bab36af96b535614b6a3 to your computer and use it in GitHub Desktop.
Integrate flask with django orm

Django ORM

(https://gist.github.com/seanbehan/168a277a5a23086e76000a59e54fb3d5)

Integration into flask

  1. Create manage.py and settings.py in the root directory. Then install the dependencies in your environment.
    pip install flask django dj-database-url psycopg2
    
    # manage.py
    import os
    import sys
    import dotenv
    
    dotenv.load_dotenv()
    
    if __name__ == "__main__":
        from django.core.management import execute_from_command_line
        execute_from_command_line(sys.argv)
    # settings.py
    import os
    import dj_database_url
    
    DATABASES = { 
        'default': dj_database_url.config(default=os.environ['DATABASE_URL']) 
    }
    
    INSTALLED_APPS = ( 'instagram', )
    
    SECRET_KEY = os.environ['SECRET_KEY']
    # .env
    
    DJANGO_SETTINGS_MODULE=settings
    DATABASE_URL="postgres://localhost:5432/<db_name>"
    SECRET_KEY=""
  2. Create a folder with the name state in your INSTALLED_APPS and create the file in the folder as below.
    django-nextagram/
        instagram_api/
        instagram_web/
        instagram/
            migrations/
                __init__.py     # empty file 
            models/
                __init__.py     # import models
                base_model.py
                user.py
        .env
        app.py
        config.py
        manage.py
        settings.py
        ...
    
  3. Add the code below in app.py to load the apps with configuration.
    # app.py
    from django.apps import apps
    from django.conf import settings
    
    apps.populate(settings.INSTALLED_APPS)

Declaring models

  1. Indexes (https://docs.djangoproject.com/en/3.0/ref/models/options/#django.db.models.Options.indexes)

    class Meta:
        indexes = [
            models.Index(fields=['username', 'email']),
        ]
  2. Model field reference https://docs.djangoproject.com/en/dev/ref/models/fields/

  3. Differentiate null=True and blank=True https://stackoverflow.com/questions/8609192/differentiate-null-true-blank-true-in-django

Migration

  1. Creating new migrations based on the changes you have made to your models
    python manage.py makemigrations
    
  2. Applying and unapplying migrations
    python manage.py migrate
    
  3. lists all migrations and their status
    python manage.py showmigrations
    
  4. Reversing migrations
    python manage.py migrate <installed_app_name> <migration_file>
    

CRUD

QuerySet API reference : (https://docs.djangoproject.com/en/3.0/ref/models/querysets/) Read more here : (https://books.agiliq.com/projects/django-orm-cookbook/en/latest/)

  1. Create
    User(username="helloworld").save()
    User.objects.create(username="helloworld")
  2. Read
    # single object
    user = User.objects.get(username="helloworld")
    # multiple object
    users = User.objects.all() # select all users
    users = User.objects.filter() # select all users
    images = Image.objects.filter(user=1, id=1) # select with filter
    images = Image.objects.filter(user=1).exclude(id=1) # select with filter and exclude
    backref => related_name
    # image.py
    class Image(BaseModel):
        user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="images")
    
    # flask shell
    for image in User.objects.get(id=1).images.all():
        print(image.id)
    join => select_related
    donation = Donation.objects.select_related('image__user').get(id=1)
    image = donation.image  # Doesn't hit the database.
    user = image.user   # Doesn't hit the database.
  3. Update
    user = User.objects.get(id=1)
    user.username = "new_name"
    user.save()
    # update multiple at once
    Image.objects.filter(user=1).update(user=2) # return number of rows updated
  4. Delete
    # delete single object
    User.objects.get(id=1).delete()
    # delete multiple at once
    Image.objects.filter(user=1).delete()
  5. Ways to get SQL query
    print(User.filter().query)
    User.filter().query.sql_with_params()
    

Deployment

Add the environment variable below to disable the collectstatic during a deploy.

# .env

DISABLE_COLLECTSTATIC=1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment