Login

Add custom fields to the built-in Group model

Author:
jmoppel
Posted:
December 19, 2022
Language:
Python
Version:
3.2
Score:
1 (after 1 ratings)

Add fields and extend Django's built-in Group model using a OneToOneField (i.e. a profile model). In this example, we add a UUIDField. Whenever a new group is created, we automatically (via signals) create a corresponding Role record referencing the newly created group. Whenever a Group is deleted, the corresponding Role is deleted as well.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from uuid import uuid4
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver

class Role(models.Model):
    """Extension of Django's built-in Group model

    Adds a UUID field to Django's built-in Group model.
    """

    uuid = models.UUIDField(
        auto_created=True,
        default=uuid4,
        editable=False,
        help_text="object ID",
        primary_key=True,
        unique=True,
    )
    group = models.OneToOneField(Group, on_delete=models.CASCADE)

    def __str__(self):
        return f"{self.group.name}"


@receiver(post_save, sender=Group)
def create_role(sender, instance, created, **kwargs):
    if created:
        Role.objects.create(group=instance)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 1 month, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 month, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 8 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 1 week ago
  5. Help text hyperlinks by sa2812 10 months ago

Comments

Please login first before commenting.