Login

Tag "foreignkey"

Snippet List

Hand over model instance relations to another instance of the same model

If you have a model instance you want to merge into another, it's handy to hand over all the relations into the model you want to merge into, so the deletion won't trigger cascading deletions from other tables. You can pass an `Iterable` of the same objects (a.k.a `QuerySet`) to the model, and then process it with the new model's `pk`.

  • foreignkey
  • many2many
  • relations
  • handover
Read More

django admin filter for GenericForeignKey field

Simple filter for django ModelAdmin How use: #models.py class ObjectWithGenericForeignKey(model.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object= GenericForeignKey('content_type', 'object_id', for_concrete_model=False) #admin.py class CommentAdmin(admin.ModelAdmin): list_filter = (get_generic_foreign_key_filter(u'Filter title'),)

  • filter
  • django
  • foreignkey
  • django-admin
Read More

ForeignKey filterspec

Unfortunately, it is not possible currently to use foreign keys in list filter of the admin website. list_filter=['city__country'] doesn't work. This filter spec tries to workaround this problem. It is also possible to have 2 filters for a foreign-key field but it requires to add a dummy field to the model. Set the fk_filterspec dictionnary on this dummy field and add 'fk':'real-field' to the dict.

  • foreignkey
  • django-admin
  • filterspec
Read More

Improved generic foreign key manager 2

This is an improvement on [snippet 1079](http://www.djangosnippets.org/snippets/1079/). Please read its description and [this blog post](http://zerokspot.com/weblog/2008/08/13/genericforeignkeys-with-less-queries/) for any information. This is a manager for handling generic foreign key. Generic foreign objects of the same type are fetched together in order to reduce the number of SQL queries. To use, just assign an instance of GFKManager as the objects attribute of a model that has generic foreign keys. Then: `MyModelWithGFKs.objects.filter(...).fetch_generic_relations()` The generic related items will be bulk-fetched to minimize the number of queries. **Improvement:** Problem I had with previous version from snippet 1079 : if two or more items shares the same generic foreign object, then only the first one is cached. Next ones generates new unwanted SQL queries. I solved this problem by putting all the needed foreign objects in a temporary data_map dictionary. Then, the objects are distributed to every items, so that if two items shares the same foreign object, it will only be fetched once.

  • foreignkey
  • generic
  • manager
  • query
  • tuning
Read More

URL models

You can use `UrlModel` to provide URL functionality to any instance of any model and any language (language support can be removed from this). Each model must have own view method, that returns HttpResponse. I was inspired by Flatpages. It is useful for small sites and static pages. `class Page(UrlModel): text = models.TextField() def view(self, request) # do something here return HttpResponse(...)`

  • middleware
  • urls
  • models
  • foreignkey
  • model
  • generic
  • url
  • foreign-key
  • genericforeignkey
  • contenttypes
  • 404
  • contenttype
  • content-type
Read More

User manager

If you have a model with foreign key to User, you can use this manager to show (i.e. in admin interface) only objects, that are related to currently logged-in user. Superuser sees all objects, not only his. Requires: [ThreadlocalsMiddleware](http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser)

  • filter
  • foreignkey
  • user
  • manager
  • queryset
  • owner
  • users
  • user-foreign-key
Read More

another UserForeignKey

This is another foreign key to User model. User is automatically associated before save. Requires: [ThreadlocalsMiddleware](http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser) Inspired by: [snippet 509](http://www.djangosnippets.org/snippets/509/)

  • foreignkey
  • model
  • user
  • field
  • users
  • user-foreign-key
Read More

Filtering foreignkey fields in django admin

Sometimes you need to filter foreignkey choices in admin interface, to objects created by user or meeting some other condition. In django 1.0 there is no formfield_for_foreignkey method in ModelAdmin class so we have to make a workaround. Here is the solution I have found to be the easiest for me.

  • filter
  • admin
  • foreignkey
Read More

Prefill ForeignKey caches

Provides an efficient means of looking up multiple related model instances for a range of objects by pre-filling the cache attribute used by `SingleRelatedObjectDescriptor` with either complete model instances or a dict containing only specified fields, looking up all required data with a single query. Example usage: C:\django_projects\soclone>django-admin.py shell >>> from soclone.models import Question >>> from soclone.views import populate_fk_caches >>> from django.db import connection >>> from django.contrib.auth.models import User >>> q = Question.objects.get(id=1) >>> a = list(q.answers.all()) >>> connection.queries = [] >>> populate_fk_caches(User, ( ... ((q,), ('author', 'last_edited_by', 'closed_by')), ... (a, ('author', 'last_edited_by')), ... ), ... fields=('username', 'gravatar', 'reputation', 'gold', 'silver', ... 'bronze')) >>> connection.queries [{'time': '0.000', 'sql': u'SELECT "auth_user"."id", "auth_user"."username", "au th_user"."gravatar", "auth_user"."reputation", "auth_user"."gold", "auth_user"." silver", "auth_user"."bronze" FROM "auth_user" WHERE "auth_user"."id" IN (1, 2)' }]

  • foreignkey
  • cache
  • prefill
Read More

improved generic foreign key manager

This is an improvement on [snippet 984](http://www.djangosnippets.org/snippets/984/). Read it's description and [this blog post](http://zerokspot.com/weblog/2008/08/13/genericforeignkeys-with-less-queries/) for good explanations of the problem this solves. Unlike snippet 984, this version is able to handle multiple generic foreign keys, generic foreign keys with nonstandard ct_field and fk_field names, and avoids unnecessary lookups to the ContentType table. To use, just assign an instance of GFKManager as the objects attribute of a model that has generic foreign keys. Then: MyModelWithGFKs.objects.filter(...).fetch_generic_relations() The generic related items will be bulk-fetched to minimize the number of queries.

  • foreignkey
  • generic
  • manager
  • query
  • tuning
Read More

Manager method for limiting GenericForeignKey queries

This is a simple manager that offers one additional method called `relate`, which fetches generic foreign keys (as referenced by `content_type` and `object_id` fields) without requiring one additional query for each contained element. Basically, when working with generic foreign keys (and esp. in the usecase of having something like a tumblelog where you use an additional model just to have a single sorting point of multiple other models), don't do something like `result = StreamItem.objects.select_related()` but just fetch the content type with `result = StreamItem.objects.select_related('content_type')`, otherwise you will end up with first one query for the list of StreamItems but then also with one additional query for each item contained in this resultset. When you now combine the latter call with `result = StreamItem.gfkmanager.relate(result)`, you will just get the one query for the item list + one query for each content type contained in this list (if the models have already been cached). For further details, please read [this post](http://zerokspot.com/weblog/2008/08/13/genericforeignkeys-with-less-queries/) on my blog.

  • foreignkey
  • generic
  • manager
  • query
  • tuning
Read More

EditInline for GenericForiegnKey II

This is an update to [snippet 765](http://www.djangosnippets.org/snippets/765/) as I was having trouble getting it to work on branches/newforms-admin @ r7771. There are just a few minor changes to the previous snippet, all simple stuff. I went ahead an added can_delete and can_order options that the previous snippet didn't include. [More details in blog post](http://paltman.com/2008/06/29/edit-inline-support-for-generic-relations/).

  • admin
  • foreignkey
  • generic
  • edit-inline
Read More

EditInline for GenericForeignKey

A simple InlineModelAdmin class that enables you to edit models that are bound by the instance via a generic foreign key (`content_type`, `object_id` pair) Use like: class PlacementInlineOptions( generic.GenericTabularInline ): model = Placement extra = 2 ct_field_name = 'target_ct' id_field_name = 'target_id' Can be also found at #4667

  • admin
  • foreignkey
  • generic
  • edit-inline
Read More

UserForeignKey

Many models are tightly coupled to the default Django `User` model (`django.contrib.auth.models.User`). Sometimes this user model just doesn't fit everyone's needs. By using `UserForeignKey` it is possible to make the `User` model configurable, encouraging loose coupling. Additionally, this can help to prevent circular imports between `User` and another model. Use it like a standard `ForeignKey`... it accepts all the same arguments. If you want to use a `User` model other than the default, just add `USER_MODEL` to your settings file.... it uses dotted notation (`app_label.model_name`). Example: class BlogPost(models.Model): user = UserForeignKey(related_name="blog_posts") title = models.CharField(...) content = models.TextField(...)

  • foreignkey
  • user
  • auth
Read More

Cached lookup model mixin

This mixin is intended for small lookup-style models that contain mostly static data and referenced by foreign keys from many other places. A good example is a list of Payment options in an e-shop that is referenced from Orders and is hitting database `order.payment` at least one time for an order. The idea is to cache entire table in a dict in memory that will live for entire life of a whole process serving many requests. The downside is that you need to restart the server when a cached lookup table changes.

  • foreignkey
  • cache
  • lookup
  • parent
Read More

18 snippets posted so far.