Login

Tag "model"

Snippet List

Decoupling models with cross-database relations

The snippet enables decoupling model classes, associated with a ForeignKey, for the purpose of separating them into two databases. Looking at the following example: class Reporter(models.Model): ... class Article(models.Model): reporter = models.ForeignKey(Reporter) We want to separate the `Reporter` and `Article` into two separate databases, but this won't work in Django because of the [cross model relations](http://docs.djangoproject.com/en/dev/topics/db/multi-db/#cross-database-relations). The solution is to use an ID field and not a `ForeignKey` one. This makes the access very uncomfortable. The above class will make this a bit less awkward. It doesn't support the [RelatedManager](http://docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.related.RelatedManager), but it will support accessing the related field as you normally would. The article class will look like this (assuming the reporter model id field is an `IntegerField`): class Article(DecoupledModel): reporter_id = models.IntegerField() _linked_fields = { 'reporter': Reporter, } Once you have an article object, you can access the reporter as you normally would for both read and writing. For example: my_reporter = article1.reporter article2.reporter = my_reporter

  • django
  • model
  • database
Read More

See what depends on a given model

Riffing on http://djangosnippets.org/snippets/1024/ I didn't want a graph; I just wanted to see what depended on a specific model. This does that nicely.

  • model
  • orm
  • dependency
Read More

Improved Pickled Object Field (Fixed for Django 1.2)

Small changes to [Snippet 1694](http://djangosnippets.org/snippets/1694/) to that QueryAPI works for django 1.2 and higher. Changes: * Replaced `get_db_prep_value` with `get_prep_value`. * Replaced `get_db_prep_lookup` with modified `get_prep_lookup`.

  • model
  • db
  • orm
  • database
  • pickle
  • object
  • field
  • type
  • pickled
  • store
Read More

Automatic CRUD urls from your models...

Just extends your models from this One... is abstract so, it will not generate a table. Now, in your urls.py do this: from django.conf.urls.defaults import * from animals.models import Dog, Cat, Bird urlpatterns = patterns('animals.views', url(r'^$', 'index', {},Dog._meta.app_label), ) dog=Dog() cat=Cat() bird=Bird() urlpatterns+=dog.build_generic_CRUD_urls(Dog) urlpatterns+=cat.build_generic_CRUD_urls(Cat) urlpatterns+=bird.build_generic_CRUD_urls(Bird) then you can create the templates, and get the urls like this: {{ object.get_absolute_url }} View {{ object.get_update_url }} Edit {{ object.get_delete_url }} Delete {{ dummy_object.get_create_url }} Create dummy_object is a quick and dirty solution until I find some better... With all these you can create 54 functional and low detail CRUDS in one hour. :D Enjoy!

  • model
  • url
  • generation
Read More

Modifying the fields of a third/existing model class

You can extend the class **ModifiedModel** to set new fields, replace existing or exclude any fields from a model class without patch or change the original code. **my_app/models.py** from django.db import models class CustomerType(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class Customer(models.Model): name = models.CharField(max_length=50) type = models.ForeignKey('CustomerType') is_active = models.BooleanField(default=True, blank=True) employer = models.CharField(max_length=100) def __unicode__(self): return self.name **another_app/models.py** from django.db import models from django.contrib.auth.models import User from this_snippet import ModifiedModel class City(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class HelperCustomerType(ModifiedModel): class Meta: model = 'my_app.CustomerType' description = models.TextField() class HelperCustomer(ModifiedModel): class Meta: model = 'my_app.Customer' exclude = ('employer',) type = models.CharField(max_length=50) # Replaced address = models.CharField(max_length=100) city = models.ForeignKey(City) def __unicode__(self): return '%s - %s'%(self.pk, self.name) class HelperUser(ModifiedModel): class Meta: model = User website = models.URLField(blank=True, verify_exists=False)

  • fields
  • model
  • helper
  • change
Read More

model instance to sql insert statement

This function will take a model instance and return an insert statement for it. I use it for extracting a subset of my production data so that I can reproduce problems in a local environment. The quoting is for mysql, you may have to change it depending on your db backend. Also, it assumes the 'default' database.

  • sql
  • model
  • db
Read More

JsonObjectField

This fields.py file defines a new model field type, "JsonObjectField," which is designed to allow the storage of arbitrary Python objects in Django TextFields. It is intended primarily to allow the storage of Python dictionaries or list objects. As the name implies, it converts objects to JSON for storage; this conversion happens transparently, so from your model's perspective, the field stores and retrieves the actual objects.

  • model
  • json
  • database
  • object
Read More

Model merging function

Generic function to merge model instances. Useful when you need to merge duplicate models together, e.g. for users. Based on http://djangosnippets.org/snippets/382/, with several enhancements: * *Type checking*: only Model subclasses can be used and testing that all instances are of same model class * *Handles symmetrical many-to-may*: original snippet failed in that case * *Filling up blank attrs of original when duplicate has it filled* * *Prepared to use outside of command-line*

  • django
  • model
  • generic
  • related
  • merge
Read More

Faster pagination / model object seeking (10x faster infact :o) for larger datasets (500k +)

ModelPagination Designed and Coded by Cal Leeming Many thanks to Harry Roberts for giving us a heads up on how to do this properly! ---------------------------------------------------------------------------- This is a super optimized way of paginating datasets over 1 million records. It uses MAX() rather then COUNT(), because this is super faster. EXAMPLE: >>> _t = time.time(); x = Post.objects.aggregate(Max('id')); "Took %ss"%(time.time() - _t ) 'Took 0.00103402137756s' >>> _t = time.time(); x = Post.objects.aggregate(Count('id')); "Took %ss"%(time.time() - _t ) 'Took 0.92404794693s' >>> This does mean that if you go deleting things, then the IDs won't be accurate, so if you delete 50 rows, you're exact count() isn't going to match, but this is okay for pagination, because for SEO, we want items to stay on the original page they were scanned on. If you go deleting items, then the items shift backwards through the pages, so you end up with inconsistent SEO on archive pages. If this doesn't make sense, go figure it out for yourself, its 2am in the morning ffs ;p Now, the next thing we do, is use id seeking, rather then OFFSET, because again, this is a shitton faster: EXAMPLE: >>> _t = time.time(); x = map(lambda x: x, Post.objects.filter(id__gte=400000, id__lt=400500).all()); print "Took %ss"%(time.time() - _t) Took 0.0467309951782s >>> _t = time.time(); _res = map(lambda x: x, Post.objects.all()[400000:400500]); print "Took %ss"%(time.time() - _t) Took 1.05785298347s >>> By using this seeking method (which btw, can be implemented on anything, not just pagination) on a table with 5 million rows, we are saving 0.92s on row count, and 1.01s on item grabbing. This may not seem like much, but if you have 1024 concurrent users, this will make a huge difference. If you have any questions or problems, feel free to contact me on cal.leeming [at] simplicitymedialtd.co.uk

  • model
  • pagination
  • object
  • large
  • big
  • dataset
  • faster
  • optimized
  • quicker
  • seeking
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

adding fields to User model

This code adds new field to Django user model. It must be executed early as much as possible, so put this code to __init__.py of some application.

  • fields
  • model
  • user
  • auth
  • field
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

137 snippets posted so far.