4

I am trying to add a search field to the Django admin model CreditsAdmin that will allow me to search the email of related customer objects. The Customer object has a generic foreign key to many different typed of object all of which have an email.

I've already tried defining the function customer_email on the Customer object and using it as a search field, but this gives the error Related Field got invalid lookup: customer_email

class Customer(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    @property
    def customer_email(self):
        return str(self.content_object.email)


class Credits(models.Model):
    credits_remaining = models.IntegerField()
    current_period_start = models.DateTimeField()
    current_period_end = models.DateTimeField()
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)


class CreditsAdmin(admin.ModelAdmin):
    list_display = (
        'current_period_start',
        'current_period_end',
        'customer_name',
        'credits_remaining',
    )

    search_fields = ('customer__customer_email',)

I'd like to be able to search the emails of related generic objects on the Customer model from the CreditsAdmin interface. In particular, one of the content_types that the customer objects relate to is django's auth.User model, but there are also others.

1 Answers1

4

You cannot use property in search_fields, because it looks for columns in database level.

GenericRelation might be a solution. You can create fields in related(by content type) models. For example:

class CntObject(models.Model):
    customers = GenericRelation(Customer, related_query_name='cnt_objects')

And in admin panel for Credits:

class CreditsAdmin(admin.ModelAdmin):
list_display = (
    'current_period_start',
    'current_period_end',
    'customer_name',
    'credits_remaining',
)

search_fields = ('customer__cnt_objects__email',)

There is a not best thing with this answer. You must be sure that all related content_objects will have email field. May be issues with performance, didn't test it.

Other solution might be, your custom get_search_results method in admin class.