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.