Login

Most bookmarked snippets

Snippet List

DRF - Optimizing ModelViewSet queries

Using Django REST Framework for Model views there is always the issue of making duplicated queries without either prefetching the objects that will be accessed using the serializer and as such will lead to large number of queries being made to the database. This will help in optimizing the queryset used for the viewset by accessing the `_meta.fields` property of the serializer.

  • django
  • rest
  • rest-api
  • django-rest-framework
Read More

Reset Postgres Sequences On Every Migrate

If you create alot of data via fixtures or by inserting the pk you will more than likely see alot of issues with the sequences being out in postgres when creating new records. Similar to: Foo with the pk(x) already exists This you have to fix by updating the postgres sequences to start at the correct number. The below will ensure after every migrate all sequences in predefined apps get reset.

  • postgres
Read More

Generic CBV Permissions Helper

A permission helper that can be included in any generic CBV, it uses the model attribute of the class to load all the permissions and tests a user can perform that action before dispatching the view.

  • permissions
Read More

CBV decorator from view function decorator

The Mixin approach for applying permissions to CBV views suffers from 3 issues: 1. you need to read the code to see what permissions are being applied to a View 2. multiple bits of disparate code required to specify, e.g., a simple permission check 3. permissions set on a base class are overridden by permission set on sub-class, unless special care is taken Here's a nice trick, using only built-in django machinery, apply a decorator intended to decorate a django view function to a CBV view. https://docs.djangoproject.com/en/1.11/topics/class-based-views/intro/#decorating-the-class This approach works for any function decorators with arguments - simply wrap it in a function that takes the same arguments: def my_cbv_decorator(*args **kwargs): return method_decorator(a_view_function_decorator(*args, **kwargs), name='dispatch') Use your new CBV decorator to decorate View sub-classes: @my_cbv_decorator('some_parameter') class MyCBView(django.views.generic.TemplateView): pass # dispatch method for this view is now wrapped by a_view_function_decorator Note: you can also pass decorator parameter directly to method_decorator, but wrapping it up like this makes the code read nicer.

  • view
  • decorator
  • permissions
  • cbv
Read More

Convert tab indented string to dictionary

output: ``` {u'Ogrenci': [u'Tum okullar', u'Lisans', u'Onlisans', u'Yuksek Lisans / Doktora', u'Ingilizce Hazirlik'], u'Ogretim Elemani': [u'Tum okullar', u'Lisans', u'Onlisans', u'Yuksek Lisans / Doktora', u'Ingilizce Hazirlik']} ```

  • python
  • tab
Read More

Automigrate, autocreatesuperuser if not User.count() in runserver and use manage.py:main as entrypoint

With this awesome manage.py, it will try to migrate first when called with runserver. Also, this manege.py has super power to be used in your entry point as such: entry_points = { 'console_scripts': [ # u haz a setup.py -> u haz importable module :) 'yourcommand = yourproject.manage:main', ], }, Example output: $ yourcommand runserver Operations to perform: Apply all migrations: auth, contenttypes, admin, sessions Running migrations: Rendering model states... DONE Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying sessions.0001_initial... OK Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. Performing system checks... Username (leave blank to use 'jpic'): Email address: [email protected] Password: Password (again): Superuser created successfully. Welcome in 2017, where automation is king System check identified no issues (0 silenced). September 17, 2017 - 21:21:41 Django version 1.9.10, using settings 'crudlfap_example.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Extra note: it doesn't matter if migrate crashes for now, since django runserver doesn't support not being able to connect to database. So most of the time I hope to shouldn't need to disable this hack.

  • django
  • manage
  • managepy
Read More

Compact primary keys

If the primary key on a table is an integer, it can be desirable after a lot of adding and removing either during testing (as was my case) or otherwise, to tidy up the key space a little and see the primary keys run up as unbroken sequences from 1. An excellent snippet here: https://djangosnippets.org/snippets/2915/ showed us how change the primary key value from in a given table and in all tables that relate to it (have a foreign key pointing into it). We can exploit that to achieve this outcome with integrity. For any given table we just fetch the primary keys into a sorted list and then walk the list assigning key 1, 2, 3, 4 etc where needed (if it doesn't already have that key).Because our list is sorted we're always moving tuples down the ladder of available keys to next empty slot basically until we've compacted the whole list. And voila. Mission accomplished. Works in with database introspection, in part because the integrity of relations is a little obscured by the ORM which hides intermediary tables in ManyToMany relationships and such. At the database API level these concerns all disappear. Built and tested with Django 1.11 but the form only goes to 1.10 here. Not even sure it works on 1.10. Certainly the snippet I based it on didn't work in 1.11 and need some updating.

  • primary-key
  • compact
Read More

3110 snippets posted so far.