Implement Django REST TokenAuthentication for Multiple User Model

I need to implement TokenAuthentication using Custom user model Consumer & Merchant (The default User model still exists and is used for admin login).

I've been looking on official DRF documentation and days looking on google, but I can't find any detailed reference about how to achieve this, all of the references I found using default User or extended User models.

class Consumer(models.Model):
    consumer_id = models.AutoField(primary_key=True)
    token = models.UUIDField(default=uuid.uuid4)
    email = models.CharField(max_length=100, unique=True, null=True)
    password = models.CharField(max_length=500, default=uuid.uuid4)


class Merchant(models.Model):
    merchant_id = models.AutoField(primary_key=True)
    token = models.UUIDField(default=uuid.uuid4)
    email = models.CharField(max_length=100, unique=True)
    name = models.CharField(max_length=100)
    password = models.CharField(max_length=500, default=uuid.uuid4)

Settings.py

INSTALLED_APPS = [
...
    'rest_framework',
...

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ],
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework.parsers.JSONParser'
    ]
}

I'm also using @api_view decorator with function-based views:

@api_view(['POST'])
@renderer_classes([JSONRenderer])
def inbound_product(request, pid):
    product = MerchantProduct.objects.get(product_id=pid)

It's recommended to keep authentication data only on one table even if you have multiple user profile tables.So in you case I think you need to have another table for authenticating the users, the table should implement AbstractBaseUser. And there should be a OneToOne reference between the merchant and customer tables to the new created user model. In this case your authentication data will only be kept on one place which is the new table . please check the following docs link for more info regarding custom authentication models and backends

Back to Top