DEV Community

loading...
Cover image for Multiple User Types With Custom Data Fields for Django

Multiple User Types With Custom Data Fields for Django

danielfeldroy profile image Daniel Feldroy Originally published at youtu.be ・1 min read

How to add custom data fields to multiple user types with Django in a maintainable way that lets us easily use Django forms or DRF serializers. Features an exciting ending with a coffee cup!

Continues from where the "Multiple User Types | Django video finishes. Watch that video at on youtube.

Code from the video, with full source code available on github:

class SpyMore(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    gadgets = models.TextField()


class Spy(User):
    base_type = User.Types.SPY
    objects = SpyManager()

    class Meta:
        proxy = True

    def whisper(self):
        return "whisper"


class DriverMore(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    model = models.CharField(max_length=255)
    make = models.CharField(max_length=255)
    year = models.IntegerField()


class Driver(User):
    base_type = User.Types.DRIVER
    objects = DriverManager()

    @property
    def more(self):
        return self.drivermore

    class Meta:
        proxy = True

    def accelerate(self):
        return "Go faster"

Tell me what intermediate-to-advanced topic you want me to cover next!

Discussion (0)

pic
Editor guide