Reputation: 118
I would display some fields from a remote table according a common field (emails) between my models. I resume:
My Django project displays a main table Prospect, related to another table Email (ForeignKey). Stored in my default Django DB (Postgres).
Then I can display in another app a remote table from a third emailing tool, stored in a MySQL database, thanks to Django databases router system. All this coexists very well in my Django admin.
Now I would display in my Prospect admin forms some fields from my remote table, in read only of course. In SQL/PHP, simplifying, I would do something like that:
SELECT myfield FROM MyRemoteTable WHERE email = {EmailValue}
But where and how can I do that with Django? I think to a special method in my Email model, but... not easy!
EDIT:
As suggested by AKX, I start to add a special method in my EmailInLine:
class EmailInLine(admin.TabularInline):
model = Email
extra = 0
readonly_fields=('get_test1', )
def get_test1(self, obj):
return "xxx"
get_test1.short_description = 'Test 1'
This displays "xxx" in my tabular sub-form, at right of each emails, good.
OK so now I have to find how write a Python query to recover my remote fields related, using each emails as variable in my query.
THX in advance
Upvotes: 0
Views: 40
Reputation: 118
I am very proud, combining official Django doc and some syntaxes tests (...), I do exactly what I would.
Here for example, I display 2 external fields in my Email tabular forms (it means before you managed multi-DB and a Django router db, and created an app with a model from a remote table). Then in admin.py:
from MyAppFromExternalDB.models import MyModelFromRemoteTable
...
class EmailInLine(admin.TabularInline):
model = Email
extra = 0
readonly_fields=('get_ExternalField1', 'get_ExternalField2')
def get_ExternalField1(self, obj):
for temp_var in MyModelFromRemoteTable.objects.raw('SELECT subid FROM external_table WHERE email LIKE %s', [obj.email]):
return temp_var.ExternalField1
get_ExternalField1.short_description = 'ExternalField1'
def get_ExternalField2(self, obj):
for temp_var in MyModelFromRemoteTable.objects.raw('SELECT subid FROM external_table WHERE email LIKE %s', [obj.email]):
return temp_var.ExternalField2
get_ExternalField2.short_description = 'ExternalField2'
Upvotes: 0
Reputation: 169388
Since ModelAdmin
's readonly_fields
allows for callables in the admin class, you can do something like
class ProspectAdmin(ModelAdmin):
readonly_fields = (...,'external_email_info')
#...
def external_email_info(self, instance: Prospect):
return get_that_external_info(instance)
iirc, you can also return an html string that's been mark_safe
d, if you need to render a widget.
Upvotes: 1