Vijay
Vijay

Reputation: 974

Display only unique records in django model admin form other model

I have a model called A with following fields

class A(models.Model):
     f_name = models.CharField(max_length=30, null=True, blank=True)
     l_name = models.CharField(max_length=30, null=True, blank=True)
     email = models.EmailField(unique=False)
     phone = models.CharField(max_length=30, null=True, blank=True)

Now I'm creating another model B from model A

class B(A):
    class Meta:
        proxy = True

admin class for B is

class BAdmin(admin.ModelAdmin):
     list_display = ('email','first_name', 'last_name', 'phone')

I want to display only distinct email in model B from model A in admin site?

Note: I don't want disturb model A but i want to get unique email records in BAdmin

for example records in model A

  1. [email protected] test2 xxx
  2. [email protected] test2 xxx
  3. [email protected] test3 xyz

I want to display unique records in model B admin as

  1. [email protected] test2 xxx
  2. [email protected] test3 xyz

I tried by writing queryset in BAdmin by

def queryset(self, request):
    qs = super(BAdmin, self).queryset(request)
    qs = qs.distinct('email')

    return qs

when i write above , I am getting DISTINCT ON fields is not supported by this database backend(MySQL) error is there another way to to display unique records in model B?

Upvotes: 1

Views: 1161

Answers (1)

Vinta
Vinta

Reputation: 387

You can use queryset() method in ModelAdmin class to filter what you want:

class BAdmin(admin.ModelAdmin):
    list_display = ('email', 'first_name', 'last_name', 'phone')

    def queryset(self, request):
        qs = super(BAdmin, self).queryset(request)
        qs = qs.distinct('email')

        return qs

Upvotes: 2

Related Questions