Skip to content

Instantly share code, notes, and snippets.

@Gpzim98
Last active October 31, 2017 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gpzim98/08580e5ac547d2516dd2757bb63a4d37 to your computer and use it in GitHub Desktop.
Save Gpzim98/08580e5ac547d2516dd2757bb63a4d37 to your computer and use it in GitHub Desktop.
Django General
# T1 - Exceptions
In general keep exceptions in views, not in models.
Put exceptions in models just when very necessary like to make process atomic or multiples tasks,
even in this case think if is not better split the method in multiple methos and treat exception in each method
# T2 - Always try to name the relationships
# T3 - Concentrate business logic into models methods and Managers
# T4 - Always help_text
# T4 - Use Meta.fields instead of Meta.exclude or Meta.fields=”__all__”
# T6 - Always use FileField in different folders even for the same field. When the folder is full it gets slow. See #3
# T7 - Exceptions
import logging
logging.exception('Caught an error')
If you call it in the except block, the caught exception will automatically be fully logged, including the trace.
# T8 - Exceptions
control-flow
====== ORM AND DATABASE ========
# 1 - Dont use if queryset:
if queryset.exists():
===== Transaction ======
# T1 - Django’s default behavior is to run in autocommit mode. Each query is immediately committed to the database, unless a transaction is active
# 1 - Isolating in transactions
from django.db import transaction
@transaction.non_atomic_requests
def my_view(request):
do_stuff()
or
with transaction.atomic():
do_more_stuff()
===== General =====
# 1 - Include one path in python path
sys.path.append("/etc/myfolder/")
# 2 - File field in different folders
def get_upload_path(instance, filename):
return os.path.join('account/avatars/', now().date().strftime("%Y/%m/%d"), filename)
# 3 - Annotate function will calculate and attach the result to each field
switch.switch_fixtures.annotate(soma=Sum('id', field='before_watts * before_qty'))[0].soma
4 # Complex aggregated expressions
from django.db.models import FloatField
from django.db.models import F
from django.db.models import Count, Min, Sum, Avg
switch.switch_fixtures.aggregate(soma=Sum(F('before_watts') * F('before_qty'), output_field=FloatField()))
class User(AbstractUser):
avatar = models.ImageField(blank=True, upload_to=get_upload_path)
# 5 - Minimum Django Script
import sys
import traceback
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
django.setup()
def main():
pass
if __name__ == "__main__":
main()
# 6 Searching in CHOICE FIELD
dict(Project.PROJECT_STATUS).get(projects[0].status)
# 7 Custom manager.py commands
from django.core.management.base import BaseCommand
from app.models import MyModel
class Command(BaseCommand):
help = 'Help text'
def add_arguments(self, parser):
parser.add_argument('param', nargs='+', type=str)
def handle(self, *args, **options):
for param in options['param']:
circ = MyModel.objects.get(id=int(param))
print(circ)
self.stdout.write(param)
===== triar
* all * get
* filter * first
* exclude * last
* order_by * latest
* reverse * earliest
* distinct * exists
* annotate * count
* aggregate
Unbasics
* select_related
* prefetch_related
* defer
* only
* using
* values
* values_list
* in_bulk
* bulk_create
products = products.annotate(Count('item'))
products.first().item__count # 24
grand_total = orders.aggregate(Sum('total'))
grand_total['total__sum'] #999.99
product.sale.id << Generate a extra query
Product.objects.only('field')
# Only this field
Product.objects.defer('expensive_field').get(...)
# All fields except
-========-
[in_bulk]
items = Items.objects.filter(order__ordered_at__month=...)
products_ids = items.values_list('product_id', flat=True)
products = Product.objects.in_bulk(product_ids)
-========-
F
instead of
for item in products:
item.update(smt)
products.update(purchases=F('purchases') + 1)
===
project by id
business > projects > site > **site_rooms
business >
DRF ===================
Returning Response with status and own messages:
if errors:
return Response({'errors': errors, 'null_before_values': True},
status=status.HTTP_406_NOT_ACCEPTABLE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment