Login

Tag "models"

Snippet List

models.MultipleEmailField

Define validator `multiple_email_validator` that splits value by commas and calls `validate_email` validator for each element found. Then define MultipleEmailField with this default validator and augmented max_length. Then ... use it!

  • models
  • fields
  • validators
Read More

Django model objects and querysets dehydration/hydration

Dehydrates objects that can be dictionaries, lists or tuples containing django model objects or django querysets. For each of those, it creates a smaller/dehydrated version of it for saving in cache or pickling. The reverse operation is also provided so dehydrated objects can also be re-hydrated. *Example:* >>> import pickle >>> users = list(User.objects.all()[:20]) >>> print users [<User: Indiana Jones>, <User: Bilbo Baggins>, ...] >>> pickled_users = pickle.dumps(users) >>> print len(pickled_users) 17546 >>> dehydrated_users = dehydrate(users) >>> pickled_dehydrated_users = pickle.dumps(dehydrated_users) >>> rehydrated_users = hydrate(pickle.loads(pickled_dehydrated_users)) >>> print rehydrated_users [<User: Indiana Jones>, <User: Bilbo Baggins>, ...] >>> print len(pickled_dehydrated_users) 1471

  • models
  • orm
  • queryset
  • hydrate
  • dehydrate
Read More

Admin Model Sorting

This allows you to order the models on the index page of the administration site in a custom way. This modification goes in the index method of django.contrib.admin.sites.AdminSite. I personally monkey patched it in where my models are loaded and registered with the admin site. Be careful that if you add new models you update the sorting dictionary, else you will get a key error. If no sorting is defined for an app, it will default to alphabetical order. Note that you'll probably want to also insert this into the app_index function as well. --- If you like my work, please check out my employer's site at 829llc.com - Dan

  • models
  • admin
  • sort
  • sorting
  • app-models
Read More

models.py with django_dag models for parts hierarchy

This is a portion of my code for creating a hierarchical relation between assemblies, subparts, and parts and so forth (although really, everything is a Part) The project being used is [django_dag](https://github.com/elpaso/django-dag) For the sake of example, let's use this structure: * Bike 1 * - Front Tire & Back Tire combo 000 * - - Front Tire 000 * - - Rear Tire 000 * - Frame 000 * - Gearset type 000 * - - Crank 000 * - - Rear Cassette 000 * . * Bike 2 * - Front Tire & Back Tire combo 001 * - - Front Tire 001 * - - Rear Tire 000 * - Frame 001 * - Gearset type 000 * - - Crank 000 * - - Rear Cassette 000 Using the above example, I couldn't use a MPTT structure because Gearset 000 is used in 2 different parents (bike 1 and bike 2). So I had to use the DAG [(wiki)](http://en.wikipedia.org/wiki/Directed_acyclic_graph) structure which allows multiple parents. The `Relationship` model holds the dag information, mainly a parent and child field. (Tire combo 001 is child of Bike2, front tire 001 is child of tire combo 001, etc) After get the dag structure using the `ancestors_tree` method on a Part object, I search for the BillOfMaterial info for that whole tree. In my case the Bill Of Material info is unique per assembly, so that's why there are seperate models. It becomes a bit of a pain to have to save/delete both the relationship and BoM models at the same time, and to check if one exists to create the other etc. But I've made my first 'hack' through it to have a function project, and am ready to make some revisions now.

  • models
  • hierarchy
  • dhango_dag
  • django-dag
Read More

Random object IDs using an abstract base model

To put obfuscated primary keys in any class, simply inherit from this one. For example: class Offer(ObfuscatedPKModel) You can match for these bigint primary keys in your urls.py like this: '^offer/(?P<offer_pk>[0-9\-]+)$'

  • models
  • model
  • random
  • abstract
  • primary-key
  • obfuscation
  • obfuscated
  • ID
Read More

models ColorField with clean minimal widget

A simple model ColorField that allows picking from a predefined list (currently picked up from settings.py The widget displays as a row of coloured SPAN's with the hex code inside. Simply click to choose a color. (requires jQuery in the page assigned to it's normal $ shortcut. Easy to change this is you don't use jQuery in this way)

  • models
  • admin
  • jquery
  • widget
  • custom-field
  • modelfield
Read More

Compare two instances of the same model

This compares two objects (of the same model) and returns a tuple containing dictionaries with the changed attributes. Note that ALL attributes are run through comparison, so if you are modifying non-field attributes at runtime, these will also be included. Excluded keys is a tuple containing the names if attributes you do not want to include in the comparison loop (i.e. attributes which changes are irrelevant).

  • models
  • comparison
Read More

Decouple 'help_text' attribute from field definition

I found model definitions with large number of fields with long help_text unreadable and feel that help_text doesn't really belong to field definition. With this snippet help_text attributes can live outside field definitions in inner HelpText class so field definitions become shorter and more readable. Usage: from django.db import models import readable_models class MyModel(models.Model): __metaclass__ = readable_models.ModelBase name = models.CharField('Name', max_length=30) address = models.CharField('Address', max_length=255) # ... long list of fields class HelpText: name = 'The name ...' address = 'Example: <very verbose example is here>'

  • models
  • help_text
Read More

PostgreSQL fulltext with language translations

Consider following models: class Product(models.Model): code = modeld.CharField() class ProductTrans(models.Model): product = models.ForeignKey('Product') language = models.ChoiceField(choices=settings.LANGUAGES) title = models.ChaField() description = models.ChaField() With this snippet is possible search through all translations of product at the same time (using string concatenation in trigger): Product.objects.extra( where = ['product_product.fulltext @@ to_tsquery(%s)'], params = [ 'someproduct' ] ) For PostgreSQL >=8.4 only.

  • sql
  • models
  • translations
  • model
  • full-text
  • postgres
  • postgresql
  • language
  • fulltext
  • translation
Read More

Per-Instance On-Model M2M Caching

If you are like me and you find yourself often using M2M fields for tons of other on-model methods, in templates, and views alike, try using this quick and dirty caching. I show the use of a "through" model for the m2m, but that is purely optional. For example, let's say we need to do several different things with our list of beads, the old way is... # views.py necklace = Necklace.objects.get(id=1) bead = Bead.objects.get(id=1) if bead in necklace.beads.all(): # this bead is here! # template necklace.html {% for bead in necklace.beads.all %} <li>{{ bead }}</li> {% endfor %} ...which would hit the database twice. Instead, we do this: # views.py necklace = Necklace.objects.get(id=1) bead = Bead.objects.get(id=1) if bead in necklace.get_beads(): # this bead is here! # template necklace.html {% for bead in necklace.get_beads %} <li>{{ bead }}</li> {% endfor %} Which only does one hit on the database. While we could have easily set the m2m query to a variable and passed it to the template to do the same thing, the great thing is how you can build extra methods on the model that use the m2m field but share the cache with anyone down the line using the same m2m field. I'm by no means an expert, so if there is something here I've done foolishly, let me know.

  • models
  • cache
  • m2m
  • caching
Read More

Get actual child model in multi-table inheritance

A common problem (it hit the Django mailinglist a couple of times) is that if you get `models.Topping.objects.all()`, you get a list of toppings, although they stand for other classes such as `SalamiTopping` or `CheeseTopping`. If you need the actual object, just derive `Topping` from `PolymorphicModel`, and say `topping.actual_instance`. This will give you e.g. a `SalamiTopping`. Sometimes you just want to check for the actual class. You can get it by saying `topping.content_type.model_class()`. There is a slight performance impact when creating objects because they have to be saved twice. NEWS: A good alternative to this approach is the [InheritanceManager](https://github.com/carljm/django-model-utils/blob/master/README.rst).

  • models
  • child-model
  • multi-table-inheritance
  • polymorphy
Read More

Django-admin autoregister -- automatic model registration

Automatically register models for the Django-admin. This snippet aids in the process of keeping your admin.py up-to-date with the models in your apps, have all models automatically added to the admin and reflect any future changes without updating the file. [zweckdev.com](http://zweckdev.com/)

  • django
  • models
  • admin
  • model
  • django-admin
  • autoregister
  • auto-register
Read More

93 snippets posted so far.