Home > Mobile >  In Django admin list, link the model which doesn't have relationship with object
In Django admin list, link the model which doesn't have relationship with object

Time:06-28

I have two models which doesn't have foreign key as relation but has the username column common.

class User(models.Model):
    password = models.CharField(max_length=255)
    email = models.EmailField(unique=True, blank=True)
    username = models.CharField(max_length=255)


class SessionUser(models.Model):
   username = models.CharField(max_length=255)
   last_login = models.DateTimeField(auto_now=True)

I wanted to list all users in Django admin and once clicked on individual object it should list all the session of user. How can we link the object which doesn't have foregien key relationship?

CodePudding user response:

i think leaving out the foreign key is not a good idea since there are chances of some usernames to be similar to avoid that, unique=True condition should be added.

CodePudding user response:

Make username model field unique in User model.

and Add a session_users method in list_display of UserAdmin class

from django.utils.html import format_html

class UserAdmin(admin.Modeladmin):
    # your user_admin model class
    list_display = ['other_model_fields', 'session_users']
    ...
    ...
    def session_users(self, obj):
        redirect_url = ("%s?username=%s") % (reverse('admin:<app_name>_sessionuser_changelist'), obj.username)
        return format_html('<a  href="{}">Add/View</a>', redirect_url)

This will redirect with filtered data of SessionUser model-admin.

  • Related