link_to_model
key
arg)
Shortcut for rendering a simple
<a href="{instance.get_absolute_url}">{text}</a>
,
where instance
is the row's object and text
is whatever field
you've set the column to represent.
This is primarily useful for converting the main "name" column (whatever that might be in
your specific situation) for the row into a clickable link for that item's detail view, but
it can be used to link to related models too via a key
argument.
datatable_options = { 'columns': [ # Standard use, no need to actually call the helper ("Headline", 'headline', helpers.link_to_model), # Target a related field; helper returns a new customized helper ("Blog", 'blog__name', helpers.link_to_model(key=lambda instance: instance.blog)), ], }
Note how the related case needs to give the key
argument. This follows the
idiom in Python for sorting, comparing, and mapping functions, described
here. A "key
function" is just a simple mapper: it takes a value in, and returns another.
link_to_model
uses this argument to let you accept the row's
instance
and return the foreign key you intend to link. Without the key
function, you would end up with a link to the row's instance with the text of the blog name,
which wouldn't be intuitive.
You can use this helper in your own custom callbacks if you want to avoid writing an HTML anchor tag in your Python code:
def get_column_Blog_data(self, instance, *args, **kwargs): # Simplest use, "text" will be the unicode of instance.blog return helpers.link_to_model(instance.blog) # Specify a custom text return helpers.link_to_model(instance.blog, text=instance.blog.name)