Login

Tag "models"

Snippet List

Filter on Multiple M2M Objects Simultaneously

This snippet should allow you to do queries not before possible using Django's ORM. It allows you to "Split" up the m2m object you are filtering on. This is best described by example: Suppose you have `Article` and `Tag`, where `Article` has a m2m relation with `Tag` (`related_name = 'tag'`). If I run: from django.db.models.query import Q Article.objects.filter(Q(tag__value = 'A') & Q(tag__value = 'B')) > # no results I would expect to get no results (there are no tags with both a value of 'A' and 'B'). However, I *would* like to somehow get a list of articles with tags meeting that criteria. Using this snippet, you can: from django.db.models.query import Q from path.to.qsplit import QSplit Article.objects.filter(QSplit(Q(tag__value = 'A')) & QSplit(Q(tag__value = 'B'))) > # articles with both tags So now they are split into different `Tag` entries. Notice how the `QSplit()` constructor takes a `Q` object---it's possible to give this any complicated Q-type expression.

  • models
  • q
  • m2m
  • db
  • orm
Read More

Generic Model

In this type of model you are allowed to define a model with a generic type. For instance, a location can be an address, GPS coordinates, an intersection and many others types. Using a many to many field, models can have multiple locations without worrying about the type of location referencing. New locations types can be added without changing the references in other models. This code is also used in Django's built in ContentTypes app.

  • models
  • generic
Read More

Getting dynamic model choices in newforms

This is an excerpt from the form code used on this site; the tricky bit here is making the `choices` for the `language` field get filled in dynamically from `Language.objects.all()` on each form instantiation, so that new languages can be picked up automatically. It also adds a blank choice at the beginning so that users can't accidentally ignore the field and incorrectly end up with whatever Language was first in the list. If you use this, always remember that you have to call the superclass `__init__` _before_ you set your dynamic choices, and that you need to accept `*args` and `**kwargs` so you can pass them to it. In theory, `ModelChoiceField` will solve this, but it still seems to be a bit buggy.

  • newforms
  • models
Read More

93 snippets posted so far.