Question

I've got multiple instances of a model, and each instance has a related email address. However, several instances have the same connected email address but when I put filter['email'] into my admin.py, I get a long list of the instances' emails, i.e. multiple copies of the same email in several cases.

Is there a way I can remove emails being listed multiple times? Or a way of customising the filter view into something a little nicer? (drop down menu maybe?)

I don't have a ManyToManyField relationship currently, or anything like that. I just have instances in my database with the fields name and email. My models.py looks like this:

import ldapdb.models
from ldapdb.models.fields import CharField, IntegerField, ListField

class Item(ldapdb.models.Model):
    item = CharField(db_column='item', max_length=30, primary_key=True, unique=True)
    email = CharField(db_column='mail', max_length=20)

My admin.py looks like so:

from items.models import Item
from django.contrib import admin

class ItemAdmin(admin.ModelAdmin):
    readonly_fields = ('email',)
    list_display = ('item', 'email')
    list_filter = ['email']
    search_fields = ['item']

admin.site.register(Item, ItemAdmin)

Obviously I've been looking at https://docs.djangoproject.com/en/1.3/ref/contrib/admin/ but I can't really see much by the way of customising my admin's filter view.

Was it helpful?

Solution

Can you post some of your code? I'm not entirely sure I understood the relationship between the instances to your email - is it an email field? a ForeighKey to a different model? how is there more than one if it's not a ManyToMany or similar relationship? And how is the filtering done in the admin?

EDIT Ok now I understand the problem. What you want is not possible. See for the django admin site the fact that they are the same email doesn't matter because it's still a different object. There's no way around that without either specifying that field to be unique or messing with the admin site code.

A better solution would be to configure the email as searchable in the admin model and then when you search for email example@example.com it would bring all matches back.

Another good solution is to make email a different model and link it to the Item model through a ManyToMany relationship. Then you create an EmailAdmin with a method that shows you all related items for each email.

It all depends on what you actually need. Ultimately you might want to write your own view or mess around with the admin site to modify it to what you need.

Also, you might want to change the email from CharField to EmailField. Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top