how to use django rest filtering with mongoengine - django

Hi I am starting django 1.8.3 with mongodb using mongo engine to create rest api.
I am using rest_framework_mongoengine to do so.
I wanted to use a feature of DjangoFilterBackend for same.
My code is:
models.py:
from mongoengine import *
from django.conf import settings
connect(settings.DBNAME)
class Client(Document):
name = StringField(max_length=50)
city = StringField(max_length=50)
country = StringField(max_length=200, verbose_name="Country")
address = StringField(default='')
Serializer.py
from client.models import Client
from rest_framework_mongoengine.serializers import DocumentSerializer
class ClientSerializer(DocumentSerializer):
class Meta:
model = Client
depth = 1
views.py
from rest_framework_mongoengine.generics import *
from rest_framework import filters
class ClientList(ListCreateAPIView):
serializer_class = ClientSerializer
queryset = Client.objects.all()
filter_backends = (filters.DjangoFilterBackend,)
filter_fields = ('name',)
I start getting error
QuerySet object has no attribute model
Don't know where its going wrong. If I remove filter_field It works but I can not use filter feature.
Any help would be of great use

You can also perform the filtering by overriding the get_queryset() method and creating a generic filtering function.
Here, we specify the filter fields tuple in the view as my_filter_fields on which we want to perform filtering. Then in our get_queryset(), we call a function get_kwargs_for_filtering().
get_kwargs_for_filtering() functions iterates over the fields defined in my_filter_fields and checks if this was passed in the query_params. If the field is found then a key with the field name and value as the retrieved value is set in a dictionary filtering_kwargs. After the iteration is over, this filtering_kwargs dictionary is returned to the get_queryset() method.
This filtering_kwargs dictionary is used to filter the queryset then.
from rest_framework_mongoengine.generics import *
from rest_framework import filters
class ClientList(ListCreateAPIView):
serializer_class = ClientSerializer
my_filter_fields = ('name', 'country') # specify the fields on which you want to filter
def get_kwargs_for_filtering(self):
filtering_kwargs = {}
for field in self.my_filter_fields: # iterate over the filter fields
field_value = self.request.query_params.get(field) # get the value of a field from request query parameter
if field_value:
# filtering_kwargs[field] = field_value
field = self.get_serializer().fields[field_name]
filtering_kwargs[field] = field.to_representation(field_value)
return filtering_kwargs
def get_queryset(self):
queryset = Client.objects.all()
filtering_kwargs = self.get_kwargs_for_filtering() # get the fields with values for filtering
if filtering_kwargs
queryset = Client.objects.filter(**filtering_kwargs) # filter the queryset based on 'filtering_kwargs'
return queryset

here is a good method to do this work.
firstly, you should install django_mongoengine_filter rest_framework_mongoengine
pip install django_mongoengine_filter
pip install rest_framework_mongoengine
secondly, you can write your owner Filter like this:
import django_mongoengine_filter as filters
from app.models import User
class UserFilter(filters.FilterSet):
class Meta:
model = User
fields = ['name']
finally, you can use the UserFilter like this in view class:
from app.models import User
from app.serializer import UserS # use rest_framework_mongoengine to write serializer
from app.filters import UserFilter
class UserVS(ModelViewSet):
queryset = User.objects.all()
serializer_class = UserS
# override filter_queryset function
def filter_queryset(self, queryset):
filter = UserFilter(self.request.query_params, queryset=queryset)
return filter.qs

Although the question is referring to Django 1.8. This is a question that is still important and valid in later versions of Django, DRF and MongoEngine.
At the time of this answer I am running
Django==4.1.3
djangorestframework==3.14
django-rest-framework-mongoengine==3.4.1
mongoengine==0.24.2
django-filter==22.1
# patched version of django-mongoengine-filter to support Django 4.0
# https://github.com/oussjarrousse/django-mongoengine-filter
# Pull request https://github.com/barseghyanartur/django-mongoengine-filter/pull/16
django-mongoengine-filter>=0.3.5
The idea in this answer is to add filtering support to django-rest-framework-mongoengine using django-mongoengine-filter that is an replacement or an extension to django-filter and should work the same way as django-filter.
First let's edit the project/settings.py file. Find the INSTALLED_APPS variable and make sure the following "Django apps" are added:
# in settings.py:
INSTALLED_APPS = [
# ...,
"rest_framework",
"rest_framework_mongoengine",
"django_filters",
# ...,
]
the app django_filters is required to add classes related to filtering infrastructure, and other things including html templates for DRF.
Then in the variable REST_FRAMEWORK we need to edit the values associated with the key: DEFAULT_FILTER_BACKENDS
# in settings.py:
REST_FRAMEWORK = {
# ...
"DEFAULT_FILTER_BACKENDS": [
"filters.DjangoMongoEngineFilterBackend",
# ...
],
# ...
}
DjangoMongoEngineFilterBackend is a custom built filter backend that we need to add to the folder (depending on how you structure your project) in the file filters
# in filters.py:
from django_filters.rest_framework.backends import DjangoFilterBackend
class DjangoMongoEngineFilterBackend(DjangoFilterBackend):
# filterset_base = django_mongoengine_filter.FilterSet
"""
Patching the DjangoFilterBackend to allow for MongoEngine support
"""
def get_filterset_class(self, view, queryset=None):
"""
Return the `FilterSet` class used to filter the queryset.
"""
filterset_class = getattr(view, "filterset_class", None)
filterset_fields = getattr(view, "filterset_fields", None)
if filterset_class:
filterset_model = filterset_class._meta.model
# FilterSets do not need to specify a Meta class
if filterset_model and queryset is not None:
element = queryset.first()
if element:
queryset_model = element.__class__
assert issubclass(
queryset_model, filterset_model
), "FilterSet model %s does not match queryset model %s" % (
filterset_model,
str(queryset_model),
)
return filterset_class
if filterset_fields and queryset is not None:
MetaBase = getattr(self.filterset_base, "Meta", object)
element = queryset.first()
if element:
queryset_model = element.__class__
class AutoFilterSet(self.filterset_base):
class Meta(MetaBase):
model = queryset_model
fields = filterset_fields
return AutoFilterSet
return None
This custom filter backend will not raise the exceptions that the original django-filter filter backend would raise. The django-filter DjangoFilterBackend access the key model in QuerySet as in queryset.model, however that key does not exist in MongoEngine.
Maybe making it available in MongoEngine should be considered:
https://github.com/MongoEngine/mongoengine/issues/2707
https://github.com/umutbozkurt/django-rest-framework-mongoengine/issues/294
Now we can add a custom filter to the ViewSet:
# in views.py
from rest_framework_mongoengine.viewsets import ModelViewSet
class MyModelViewSet(ModelViewSet):
serializer_class = MyModelSerializer
filter_fields = ["a_string_field", "a_boolean_field"]
filterset_class = MyModelFilter
def get_queryset(self):
queryset = MyModel.objects.all()
return queryset
Finally let's get back to filters.py and add the MyModelFilter
# in filters.py
from django_mongoengine_filter import FilterSet, StringField, BooleanField
class MyModelFilter(FilterSet):
"""
MyModelFilter is a FilterSet that is designed to work with the django-filter.
However the original django-mongoengine-filter is outdated and is causing some troubles
with Django>=4.0.
"""
class Meta:
model = MyModel
fields = [
"a_string_field",
"a_boolean_field",
]
a_string_field = StringFilter()
a_boolean_field = BooleanFilter()
That should do the trick.

Related

Combine two django models with shared ids into a single viewset

I have two django models in two independent apps, who use the same user ids from an external authentication service:
In app1/models.py:
class App1User(models.Model):
user_id = models.UUIDField(unique=True)
app1_field = models.BooleanField()
In app2/models.py:
class App2User(models.Model):
user_id = models.UUIDField(unique=True)
app2_field = models.BooleanField()
I would like to have a combined viewset that can make it seem like these two are a single model with a list response as follows:
[
{
'user_id': ...,
'app1_field': ...,
'app2_field': ...
},
...
]
If I create or update with this viewset, it should save the data to each of the two models.
To create a combined viewset for App1User and App2User models, you can
follow these steps:
Create a serializer for the combined model. In your main app, create a
serializers.py file and define the following serializer:
from rest_framework import serializers
from app1.models import App1User
from app2.models import App2User
class App1UserSerializer(serializers.ModelSerializer):
class Meta:
model = App1User
fields = ('user_id', 'app1_field')
class App2UserSerializer(serializers.ModelSerializer):
class Meta:
model = App2User
fields = ('user_id', 'app2_field')
class CombinedUserSerializer(serializers.Serializer):
user_id = serializers.UUIDField()
app1_field = serializers.BooleanField()
app2_field = serializers.BooleanField()
def create(self, validated_data):
app1_data = {'user_id': validated_data['user_id'], 'app1_field': validated_data['app1_field']}
app2_data = {'user_id': validated_data['user_id'], 'app2_field': validated_data['app2_field']}
app1_serializer = App1UserSerializer(data=app1_data)
app2_serializer = App2UserSerializer(data=app2_data)
if app1_serializer.is_valid() and app2_serializer.is_valid():
app1_serializer.save()
app2_serializer.save()
return validated_data
def update(self, instance, validated_data):
app1_instance = App1User.objects.get(user_id=validated_data['user_id'])
app2_instance = App2User.objects.get(user_id=validated_data['user_id'])
app1_serializer = App1UserSerializer(app1_instance, data={'app1_field': validated_data['app1_field']})
app2_serializer = App2UserSerializer(app2_instance, data={'app2_field': validated_data['app2_field']})
if app1_serializer.is_valid() and app2_serializer.is_valid():
app1_serializer.save()
app2_serializer.save()
return validated_data
This serializer defines the structure of the combined model and uses App1UserSerializer and App2UserSerializer to handle the fields of each model.
Create a viewset for the combined model. In your main app, create a viewsets.py file and define the following viewset:
from rest_framework import viewsets
from app1.models import App1User
from app2.models import App2User
from .serializers import CombinedUserSerializer
class CombinedUserViewSet(viewsets.ModelViewSet):
serializer_class = CombinedUserSerializer
def get_queryset(self):
app1_users = App1User.objects.all()
app2_users = App2User.objects.all()
combined_users = []
for app1_user in app1_users:
app2_user = app2_users.filter(user_id=app1_user.user_id).first()
if app2_user:
combined_user = {
'user_id': app1_user.user_id,
'app1_field': app1_user.app1_field,
'app2_field': app2_user.app2_field
}
combined_users.append(combined_user)
return combined_users
This viewset uses CombinedUserSerializer to handle the requests and retrieves the data from both App1User and App2User models. The get_queryset() method retrieves all the App1User and App2User instances, matches them based on their user_id, and creates a list of combined users.
Register the viewset in your main app's urls.py file:
# main_app/urls.py
from django.urls import include, path
from rest_framework import routers
from .views import CombinedUserViewSet
router = routers.DefaultRouter()
router.register(r'combined-users', CombinedUserViewSet)
urlpatterns = [
path('', include(router.urls)),
]
This code sets up a default router and registers the CombinedUserViewSet with the endpoint /combined-users/, which can be used to access the combined model data.
Above solution is the idea how it can be done, you can modify according to your needs. If this idea helps, plz mark this as accept solution.

django rest framework Viewset for single item, not list

I am having a problem with my DRF API. I want to provide a read only endpoint that takes a single id from a object(document) in the DB and runs a script to perform an check and gives back the result.
It works fine when I call the API with //api/documentcheck/1/ where 1 is the pk of the document in the DB.
The problem is that if I just call the base URL //api/documentcheck/ it tries to give back the results of all documents in the database and times out because it takes ages.
I am looking for a way to remove the list view and force users to provide the ID for a single document to check.
This is my serializer class
class DocumentCheckSerializer(serializers.Serializer):
'''Serializer for document check'''
class Meta:
model = Document
fields = '__all__'
def to_representation(self, value):
return process_document(value)
This is my view:
class DocumentCheck(viewsets.ReadOnlyModelViewSet):
"""Check a single document"""
authentication_classes = (
TokenAuthentication,
SessionAuthentication,
BasicAuthentication,
)
permission_classes = [IsAuthenticated]
queryset = Document.objects.all()
serializer_class = serializers.DocumentCheckSerializer
and my router entry
router.register("documentcheck", views.DocumentCheck, basename="documentcheck")
You can use just GenericViewSet and RetrieveModelMixin as your base class
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import RetrieveModelMixin
class DocumentCheck(GenericViewSet, RetrieveModelMixin):
"""Check a single document"""
authentication_classes = (
TokenAuthentication,
SessionAuthentication,
BasicAuthentication,
)
permission_classes = [IsAuthenticated]
queryset = Document.objects.all()
serializer_class = serializers.DocumentCheckSerializer

How to apply a filter backend to all fields of all resources in Django Rest Framework?

I have a lot of resources and i want to apply the DjangoFilterBackend to all of them.
Tried setting in settings.py
'DEFAULT_FILTER_BACKENDS': [
'rest_framework.filters.DjangoFilterBackend',
]
But it didn't work
I tried adding only filter_backends = (filters.DjangoFilterBackend,) to one of my resources and it still didn't work.
Only after I explicitly added filter_fields = ('col1','col2',) it started working with those fields only.
Is there any way I can apply the filter backend to all resources and all fields (same way i do with permissions for example ... ) ?
Thanks.
Right now you are telling Django REST Framework to use the DjangoFilterBackend for all views, but you are not telling it how the FilterSet should be generated.
django-filter will automatically generate a FilterSet for all of the fields on a model if the fields are set to None. Django REST Framework will automatically generate a FilterSet if filter_fields are not set to None, which means you won't be able to use the default DjangoFilterBackend.
You can create a custom DjangoFilterBackend though, which will automatically generate the FilterSet for all fields on the model.
from rest_framework.filters import DjangoFilterBackend
class AllDjangoFilterBackend(DjangoFilterBackend):
"""
A filter backend that uses django-filter.
"""
def get_filter_class(self, view, queryset=None):
"""
Return the django-filters `FilterSet` used to filter the queryset.
"""
filter_class = getattr(view, 'filter_class', None)
filter_fields = getattr(view, 'filter_fields', None)
if filter_class or filter_fields:
return super(AllDjangoFilterBackend, self).get_filter_class(self, view, queryset)
class AutoFilterSet(self.default_filter_set):
class Meta:
model = queryset.model
fields = None
return AutoFilterSet
This will still use the original filter backend for situations where the view defines a custom filter_class or filter_fields, but it will generate a custom FilterSet for all other situations. Keep in mind that you shouldn't allow fields which aren't returned through the API to be filtered, as you are opening yourself up to future security issues (like people filtering a user list by passwords).
Ok I know it was a long time ago, but I was just faced with this question today (2019/11), so I decided to share this way that I think it is a little better:
Just use '__all__' for filter fields
filter_fields = '__all__'
Kevin Browns answer is fantastic, however may be slightly out of date now.
Running the AllDjangoFilterBackend filter backend with django-filter==2.1.0 throws the following:
Setting 'Meta.model' without either 'Meta.fields' or 'Meta.exclude' has been deprecated since 0.15.0 and is now disallowed. Add an explicit 'Meta.fields' or 'Meta.exclude' to the AutoFilterSet class.
It seems that simply replacing fields = None with exclude = '' is sufficient to use all fields. Full code below:
from django_filters.rest_framework import DjangoFilterBackend
class AllDjangoFilterBackend(DjangoFilterBackend):
'''
Filters DRF views by any of the objects properties.
'''
def get_filter_class(self, view, queryset=None):
'''
Return the django-filters `FilterSet` used to filter the queryset.
'''
filter_class = getattr(view, 'filter_class', None)
filter_fields = getattr(view, 'filter_fields', None)
if filter_class or filter_fields:
return super().get_filter_class(self, view, queryset)
class AutoFilterSet(self.default_filter_set):
class Meta:
exclude = ''
model = queryset.model
return AutoFilterSet
Save this to your_project/your_app/filters.py (or similar) and then ensure your settings file contains:
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': (
'your_project.your_app.filters.AllDjangoFilterBackend'
),
}
Updated version of Stuart Buckingham comment for django-rest-framework 3.13.1:
from django_filters.rest_framework import DjangoFilterBackend
class AllDjangoFilterBackend(DjangoFilterBackend):
"""
A filter backend that uses django-filter.
"""
def get_filterset_class(self, view, queryset=None):
'''
Return the django-filters `FilterSet` used to filter the queryset.
'''
filter_class = getattr(view, 'filter_class', None)
filter_fields = getattr(view, 'filter_fields', None)
if filter_class or filter_fields:
return super().get_filter_class(self, view, queryset)
class AutoFilterSet(self.filterset_base):
class Meta:
fields = "__all__"
model = queryset.model
return AutoFilterSet

Django Admin linking to related objects

My app has users who create pages. In the Page screen of the admin, I'd like to list the User who created the page, and in that list, I'd like the username to have a link that goes to the user page in admin (not the Page).
class PageAdmin(admin.ModelAdmin):
list_display = ('name', 'user', )
list_display_links = ('name','user',)
admin.site.register(Page, PageAdmin)
I was hoping that by making it a link in the list_display it would default to link to the actual user object, but it still goes to Page.
I'm sure I'm missing something simple here.
Modifying your model isn't necessary, and it's actually a bad practice (adding admin-specific view-logic into your models? Yuck!) It may not even be possible in some scenarios.
Luckily, it can all be achieved from the ModelAdmin class:
from django.urls import reverse
from django.utils.safestring import mark_safe
class PageAdmin(admin.ModelAdmin):
# Add it to the list view:
list_display = ('name', 'user_link', )
# Add it to the details view:
readonly_fields = ('user_link',)
def user_link(self, obj):
return mark_safe('{}'.format(
reverse("admin:auth_user_change", args=(obj.user.pk,)),
obj.user.email
))
user_link.short_description = 'user'
admin.site.register(Page, PageAdmin)
Edit 2016-01-17:
Updated answer to use make_safe, since allow_tags is now deprecated.
Edit 2019-06-14:
Updated answer to use django.urls, since as of Django 1.10 django.core.urls has been deprecated.
Add this to your model:
def user_link(self):
return '%s' % (reverse("admin:auth_user_change", args=(self.user.id,)) , escape(self.user))
user_link.allow_tags = True
user_link.short_description = "User"
You might also need to add the following to the top of models.py:
from django.template.defaultfilters import escape
from django.core.urls import reverse
In admin.py, in list_display, add user_link:
list_display = ('name', 'user_link', )
No need for list_display_links.
You need to use format_html for modern versions of django
#admin.register(models.Foo)
class FooAdmin(admin.ModelAdmin):
list_display = ('ts', 'bar_link',)
def bar_link(self, item):
from django.shortcuts import resolve_url
from django.contrib.admin.templatetags.admin_urls import admin_urlname
url = resolve_url(admin_urlname(models.Bar._meta, 'change'), item.bar.id)
return format_html(
'{name}'.format(url=url, name=str(item.bar))
)
I ended up with a simple helper:
from django.shortcuts import resolve_url
from django.utils.safestring import SafeText
from django.contrib.admin.templatetags.admin_urls import admin_urlname
from django.utils.html import format_html
def model_admin_url(obj: Model, name: str = None) -> str:
url = resolve_url(admin_urlname(obj._meta, SafeText("change")), obj.pk)
return format_html('{}', url, name or str(obj))
Then you can use the helper in your model-admin:
class MyAdmin(admin.ModelAdmin):
readonly_field = ["my_link"]
def my_link(self, obj):
return model_admin_url(obj.my_foreign_key)
I needed this for a lot of my admin pages, so I created a mixin for it that handles different use cases:
pip install django-admin-relation-links
Then:
from django.contrib import admin
from django_admin_relation_links import AdminChangeLinksMixin
#admin.register(Group)
class MyModelAdmin(AdminChangeLinksMixin, admin.ModelAdmin):
# ...
change_links = ['field_name']
See the GitHub page for more info. Try it out and let me know how it works out!
https://github.com/gitaarik/django-admin-relation-links
I decided to make a simple admin mixin that looks like this (see docstring for usage):
from django.contrib.contenttypes.models import ContentType
from django.utils.html import format_html
from rest_framework.reverse import reverse
class RelatedObjectLinkMixin(object):
"""
Generate links to related links. Add this mixin to a Django admin model. Add a 'link_fields' attribute to the admin
containing a list of related model fields and then add the attribute name with a '_link' suffix to the
list_display attribute. For Example a Student model with a 'teacher' attribute would have an Admin class like this:
class StudentAdmin(RelatedObjectLinkMixin, ...):
link_fields = ['teacher']
list_display = [
...
'teacher_link'
...
]
"""
link_fields = []
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.link_fields:
for field_name in self.link_fields:
func_name = field_name + '_link'
setattr(self, func_name, self._generate_link_func(field_name))
def _generate_link_func(self, field_name):
def _func(obj, *args, **kwargs):
related_obj = getattr(obj, field_name)
if related_obj:
content_type = ContentType.objects.get_for_model(related_obj.__class__)
url_name = 'admin:%s_%s_change' % (content_type.app_label, content_type.model)
url = reverse(url_name, args=[related_obj.pk])
return format_html('{}', url, str(related_obj))
else:
return None
return _func
If anyone is trying to do this with inline admin, consider a property called show_change_link since Django 1.8.
Your code could then look like this:
class QuestionInline(admin.TabularInline):
model = Question
extra = 1
show_change_link = True
class TestAdmin(admin.ModelAdmin):
inlines = (QuestionInline,)
admin.site.register(Test, TestAdmin)
This will add a change/update link for each foreign key relationship in the admin's inline section.

How Do I Show Django Admin Change List View of foreign key children?

I'm working on an app with a Model hierarchy of Campaign > Category > Account. Ideally, I'd like users to be able to click on a link in the campaign admin list view and go to a URL like "/admin/myapp/campaign/2/accounts/" which will show a Django admin view with all the handy ChangeList amenities but which is filtered to show just the accounts in categories in the specified campaign (ie. Account.object.filter(category__campaign__id = 2)). (Note, categories themselves I'm happy to just be "filters" on this accounts list view).
I can't seem to find any reference to a way to mimic this item-click-goes-to-list-of-foriegn-key-children approach that is common in many other frameworks.
Is it possible? Is there a "better" approach in the django paradigm?
thanks for any help!
This was an interesting question so I whipped up a sample app to figure it out.
# models.py
from django.db import models
class Campaign(models.Model):
name = models.CharField(max_length=20)
def __unicode__(self):
return unicode(self.name)
class Category(models.Model):
campaign = models.ForeignKey(Campaign)
name = models.CharField(max_length=20)
def __unicode__(self):
return unicode(self.name)
class Account(models.Model):
category = models.ForeignKey(Category)
name = models.CharField(max_length=20)
def __unicode__(self):
return unicode(self.name)
# admin.py
from django.contrib import admin
from models import Campaign, Category, Account
class CampaignAdmin(admin.ModelAdmin):
list_display = ('name', 'related_accounts', )
def related_accounts(self, obj):
from django.core import urlresolvers
url = urlresolvers.reverse("admin:<yourapp>_account_changelist")
lookup = u"category__campaign__exact"
text = u"View Accounts"
return u"<a href='%s?%s=%d'>%s</a>" % (url, lookup, obj.pk, text)
related_accounts.allow_tags = True
admin.site.register(Campaign, CampaignAdmin)
admin.site.register(Category)
class AccountAdmin(admin.ModelAdmin):
list_display = ('category', 'name')
list_filter = ('category__campaign',)
admin.site.register(Account, AccountAdmin)
You'll need to replace with the name of your app where the Account ModelAdmin lives.
Note: the list_filter on the AccountAdmin is required since Django 1.2.4, Django 1.1.3 and Django 1.3 beta 1, which introduced protection from arbitrary filtering via URL parameter in the admin.
If i understand you correctly, you want to add a custom field (a callable in your ModelAdmin's list_display) to your CampaignAdmin change_list view.
Your custom field would be a link that takes the category.id of each category in your change_list and generates a link to the desired, filtered admin view, which seems to be the account-change_list in your case:
admin/yourproject/account/?category__id__exact=<category.id>
Assuming category is a field on your Campaign-Model you could add the follwoing method to your CampaignAdmin:
def account_link(self, obj):
return 'Accounts' % (obj.category.id)
account_link.allow_tags = True
And then you add it to the admin's list_display option:
list_display = ('account_link', ...)
It depends a bit on your data model though.
If you want to create a permanent, filtered change_list view that suits your needs, you may take a look at this article: http://lincolnloop.com/blog/2011/jan/11/custom-filters-django-admin/
The other solutions don't pay attention to the filters you already have applied. They are part of the query string and I wanted to retain them as well.
First you need to get a reference to the request, you can do that by wrapping changelist_view or queryset as I did:
class AccountAdmin(ModelAdmin):
model = Account
list_display = ('pk', 'campaign_changelist')
# ...
def queryset(self, request):
self._get_params = request.GET
return super(AccountAdmin, self).queryset(request)
def campaign_changelist(self, obj):
url = reverse('admin:yourapp_account_changelist')
querystring = self._get_params.copy()
querystring['campaign__id__exact'] = obj.campaign.pk
return u'{2}'.format(
url, querystring.urlencode(), obj.campaign)
campaign_changelist.allow_tags = True
And something like that will give you a filter inside the changelist rows. Really helpful. :-)
These are good solutions. I wasn't aware of the auto-filter by url paradigm. Here's another I've discovered which allows you use a custom url scheme:
from consensio.models import Account
from django.contrib import admin
from django.conf.urls.defaults import patterns, include, url
class AccountAdmin(admin.ModelAdmin):
campaign_id = 0;
def campaign_account_list(self, request, campaign_id, extra_context=None):
'''
First create your changelist_view wrapper which grabs the extra
pattern matches
'''
self.campaign_id = int(campaign_id)
return self.changelist_view(request, extra_context)
def get_urls(self):
'''
Add your url patterns to get the foreign key
'''
urls = super(AccountAdmin, self).get_urls()
my_urls = patterns('',
(r'^bycampaign/(?P<campaign_id>\d+)/$', self.admin_site.admin_view(self.campaign_account_list))
)
return my_urls + urls
def queryset(self, request):
'''
Filter the query set based on the additional param if set
'''
qs = super(AccountAdmin, self).queryset(request)
if (self.campaign_id > 0):
qs = qs.filter(category__campaign__id = self.campaign_id)
return qs
And plus you'd need to incorporate the URL link into CampaignAdmin's list view...