Skip to content

Instantly share code, notes, and snippets.

@SamDudley
Last active February 20, 2023 08:58
Show Gist options
  • Save SamDudley/f344d8392de8bee95a83f8d1de738957 to your computer and use it in GitHub Desktop.
Save SamDudley/f344d8392de8bee95a83f8d1de738957 to your computer and use it in GitHub Desktop.

Bash

# Generate 8 random characters.
cat /proc/sys/kernel/random/uuid | cut -c 1-8

Python

How isinstance works

>>> class Foo:
...     pass
... 
>>> class Bar(Foo):
...     pass
... 
>>> foo = Foo()
>>> bar = Bar()
>>> isinstance(foo, Foo)
True
>>> isinstance(foo, Bar)
False
>>> isinstance(bar, Bar)
True
>>> isinstance(bar, Foo)
True

Django

Migration

def forward(apps, schema_editor):
    MyModel = apps.get_model('myapp', 'MyModel')

def reverse(apps, schema_editor):
    MyModel = apps.get_model('myapp', 'MyModel')

Command

from django.core.management.base import BaseCommand, CommandError


class Command(BaseCommand):
    help = 'Command template'

    def add_arguments(self, parser):
        parser.add_argument('answer', type=int)

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS(f"The answer is {options['answer']}"))

BooleanField with choices

YES_NO_CHOICES = (
  (None, ""),
  (True, "Yes"),
  (False, "No"),
)

foo = models.BooleanField(choices=YES_NO_CHOICES, null=True)

Print how many queries

# FIXME: Remove debug code.
from django.db import connection

print(connection.queries)
print(len(connection.queries))

Form clean

    def clean(self):
        cleaned_data = super().clean()

        return cleaned_data

psql

# list tables
\d

# describe table
\d table_name
# or
\d+ table_name

# connect to a database
\c db_name
# or
\connect db_name

# copy to csv
\copy [Table/Query] to '[Relative Path/filename.csv]' csv header
# example
\copy (select name from public.groups) to "groups.csv" csv header

# run file
psql -f [query.sql]

# run file and output to csv
psql --csv -f [query.sql] > [query.csv]

# List all users
\du

# Turn off the pager output
\pset pager off

npm

# Update package-lock.json
npm install --package-lock-only

css

.inline-list {
  display: flex;

  > div:not(:empty) + div:not(:empty)::before {
    content: ", ";
  }

  &:has(div:not(:empty))::before {
    content: "(";
  }

  &:has(div:not(:empty))::after {
    content: ")";
  }
}
<div class="govuk-body inline-list">
    <div>foo</div><div>bar</div><div>baz</div>
</div>
<div class="govuk-body inline-list">
    <div></div><div>bar</div><div>baz</div>
</div>
<div class="govuk-body inline-list">
    <div>foo</div><div></div><div></div>
</div>
<div class="govuk-body inline-list">
    <div></div><div></div><div></div>
</div>

Notable commits

Optimisation of a large DRF query

https://github.com/uktrade/digital-workspace-v2/pull/292/files

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