【发布时间】:2019-04-17 11:13:22
【问题描述】:
我正在尝试向 Django 管理模型 CreditsAdmin 添加一个搜索字段,这将允许我搜索相关客户对象的电子邮件。 Customer 对象具有许多不同类型对象的通用外键,所有这些对象都有电子邮件。
我已经尝试在 Customer 对象上定义函数 customer_email 并将其用作搜索字段,但这会产生错误 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',)
我希望能够从CreditsAdmin 接口搜索Customer 模型上相关通用对象的电子邮件。特别是,与客户对象相关的 content_type 之一是 django 的 auth.User 模型,但还有其他的。
【问题讨论】:
标签: django django-models django-admin