Login

Tag "model"

Snippet List

Update only selected model fields

Watch out! Previous versions of this snippet (without the values list) were vulnerable to SQL injection attacks. The "correct" solution is probably to wait until [ticket 4102](http://code.djangoproject.com/ticket/4102) hits the trunk. But here's my temporary fix while we wait for that happy day. Django's model.save() method is a PITA: 1. It does a SELECT first to see if the instance is already in the database. 2. It has additional database performance overhead because it writes all fields, not just the ones that have been changed. 3. It overwrites other model fields with data that may be out of date. This is a real problem in concurrent applications, like almost all web apps. If you just want to update a field or two on a model instance which is already in the database, try this: update_fields(user, email='[email protected]', is_staff=True, last_login=datetime.now()) Or you can add it to your models (see below) and then do this: user.update_fields( email='[email protected]', is_staff=True, last_login=datetime.now()) To add it to your model, put it in a module called granular_update, then write this in your models.py: import granular_update class User(models.Model): email = models.EmailField() is_staff = models.BooleanField() last_login = models.DateTimeField() update_fields = granular_update.update_fields

  • fields
  • model
  • save
  • performance
  • field
  • update
  • integrity
  • consistency
Read More

Manager for something like __inall

Provides the method from_related_ids, which lets you select some objects by providing a list of related ids (The huge difference to __in is that the objects have to match al of the ids, not only one) Model Example:: class Article(models.Model): text = models.TextField() tags = ManyToManyField('Tag') objects = AllInManager() Usage:: Article.objects.from_related_ids((1,2,3,4), 'tags')

  • model
  • db
  • manager
Read More

filter/search a newforms select widget

Adds a filter input above a select widget that allows live-filtering on the client-side (no ajax) in Firefox. Example: make_fields_searchable(ModelItemForm, { 'publisher': {'set_size': 8}, 'developer': {'set_size': 8}, 'genre': {}, 'platform': {} })

  • filter
  • newforms
  • search
  • model
  • widgets
  • select
Read More

Instance partial update

If you're like me, you've got a models with a lot of fields/foreignkeys and often only want to edit a portion of the model in a form. Add this method to your custom form class and use it in place of the save() method.

  • forms
  • model
  • partial
  • updating
Read More

shortcut for saving newforms to model

I come up with this short cut of saving data from newforms to a model, for newforms that contains attributes from several models or some attributes that doesn't found in a model attributes

  • newforms
  • model
Read More

CompressedTextField

A CompressedTextField to transparently save data gzipped in the database and uncompress at retrieval. Full description at my blog: [arnebrodowski.de/...Field-for-Django.html](http://www.arnebrodowski.de/blog/435-Implementing-a-CompressedTextField-for-Django.html)

  • text
  • model
  • field
  • compressed
Read More

duplicate model object merging script

Use this function to merge model objects (i.e. Users, Organizations, Polls, Etc.) and migrate all of the related fields from the alias objects the primary object. Usage: from django.contrib.auth.models import User primary_user = User.objects.get(email='[email protected]') duplicate_user = User.objects.get(email='[email protected]') merge_model_objects(primary_user, duplicate_user)

  • django
  • fields
  • model
  • generic
  • related
  • merge
  • duplicates
  • genericforeignkey
Read More

JSONField

This is a great way to pack extra data into a model object, where the structure is dynamic, and not relational. For instance, if you wanted to store a list of dictionaries. The data won't be classically searchable, but you can define pretty much any data construct you'd like, as long as it is JSON-serializable. It's especially useful in a JSON heavy application or one that deals with a lot of javascript. **Example** (models.py): from django.db import models from jsonfield import JSONField class Sequence(models.Model): name = models.CharField(maxlength=25) list = JSONField() **Example** (shell): fib = Sequence(name='Fibonacci') fib.list = [0, 1, 1, 2, 3, 5, 8] fib.save() fib = Sequence.objects.get(name='Fibonacci') fib.list.append(13) print fib.list [0, 1, 1, 2, 3, 5, 8, 13] fib.get_list_json() "[0, 1, 1, 2, 3, 5, 8, 13]" *Note:* You can only save JSON-serializable data. Also, dates will be converted to string-timestamps, because I don't really know what better to do with them. Finally, I'm not sure how to interact with forms yet, so that realm is a bit murky.

  • models
  • model
  • json
  • db
  • field
  • json-field
Read More

Markup Selection in Admin

This method lets you define your markup language and then processes your entries and puts the HTML output in another field on your database. I came from a content management system that worked like this and to me it makes sense. Your system doesn't have to process your entry every time it has to display it. You would just call the "*_html" field in your template. Requires: Django .96 [Markdown](http://cheeseshop.python.org/pypi/Markdown/1.6 "Python Package Index: Markdown") [Textile](http://cheeseshop.python.org/pypi/textile "Python Package Index: Textile")

  • admin
  • model
  • markup
  • markdown
  • textile
Read More

DRY with common model fields (another way)

Some time you want to add some common fields to a group of models, for example, in a **Generalization/Specialization** relationship. One could have a base model as the generalization class and specialized models with a foreign key to that base model with an unique attribute but I don't like it that way so, I just do this code to add some commons attributes to a lot of models. If you have many models that all share the same fields, this might be an option. The fields are added directly to each model, e.g. while they will be duplicated on the database level, you only have to define them once in your **python** code. This code is a cleaner way(I think!!!) to do it and will do the same that [this one](http://www.djangosnippets.org/snippets/317/). I hope this piece of code will be useful for you.

  • models
  • model
  • dry
  • common
Read More

DRY with common model fields

If you have many models that all share the same fields, this might be an option. Please note that order matters: Your model need to inherit from TimestampedModelBase first, and models.Model second. The fields are added directly to each model, e.g. while they will be duplicated on the database level, you only have to define them once in your python code. Not sure if there is a way to automate the call to TimestampedModelInit(). Tested with trunk rev. 5699. There is probably a slight chance that future revisions might break this.

  • models
  • model
  • inheritance
Read More

Case-insensitive lookup by default

I wanted lookups on tags to be case insensitive by default, so that things like Tag.objects.get(name='Tag') would return any similar tags (ignoring case differences), i.e. `<Tag: tag>`. This snippet makes lookup on the 'name' field case-insensitive by default, although case-sensitive lookups can still be achieved with 'name__exact'. Methods like get_or_create will work as expected and be case-insensitive.

  • model
  • tags
  • tagging
  • manager
  • case-insensitive
  • iexact
  • queryset
Read More

Allow filtering and ordering by counts of related query results

I know you're thinking, *what the heck could that title mean?* I often find myself wanting to filter and order by the result of a COUNT(*) of a query using a method similar to the [entry_count example](http://www.djangoproject.com/documentation/db-api/#extra-select-none-where-none-params-none-tables-none). Writing this many times is tedious and hardcoding the table and column names made me cringe, I also wanted the counts to result from more complex queries. This is a method you can add to your custom Manager to do this easily. It's not an ideal syntax, but it's good for the amount of code required. Example: suppose we have some articles we want to filter and order by comments and visit logs to show the most popular... class ArticleManager(models.Manager): count_related = _count_related class Article(models.Model): pub_date = models.DateTimeField(auto_now_add=True) objects = ArticleManager() class Comment(models.Model): article = models.ForeignKey(Article) is_spam = models.BooleanField(default=False) class Visit(models.Model): article = models.ForeignKey(Article) referrer = models.URLField(verify_exists=False) search_query = models.CharField(maxlength=200) Notice how the ArticleManager is given the `count_related` method. Now you can find the most popular like so... Order by non-spam comments: Article.objects.count_related(Comment.objects.filter( is_spam=False)).order_by('-comment__count') Order by incoming non-search-engine links: Article.objects.count_related(Visit.objects.filter( referrer__isnull=False, search_query__isnull=True), 'links').order_by('-links') Order by total visits: Article.objects.count_related(Visit).order_by('-visit__count') Note: Doesn't work if `query` contains joins or for many-to-many relationships, but those could be made to work identically if there's demand.

  • sql
  • model
  • db
  • count
  • manager
Read More

Subclassing a model.field for newforms

The newforms fields are more capable than the django models fields. In this snippet, we subclass models.IntegerField, and add min_value and max_value. e.g. age = MMIntegerField('How old are you?', min_value=13, max_value=120)

  • newforms
  • fields
  • model
Read More

137 snippets posted so far.