Movatterモバイル変換


[0]ホーム

URL:


Login

djangosnippets

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-inGroup model using aOneToOneField (i.e. a profile model). In this example, we add aUUIDField. Whenever a new group is created, we automatically (via signals) create a correspondingRole 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 91011121314151617181920212223242526272829
fromuuidimportuuid4fromdjango.dbimportmodelsfromdjango.db.models.signalsimportpost_savefromdjango.dispatchimportreceiverclassRole(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):returnf"{self.group.name}"@receiver(post_save,sender=Group)defcreate_role(sender,instance,created,**kwargs):ifcreated:Role.objects.create(group=instance)

More like this

  1. Mask sensitive data from logger byagusmakmun 1 week, 4 days ago
  2. Template tag - list punctuation for a list of items byshapiromatron 1 year, 2 months ago
  3. JSONRequestMiddleware adds a .json() method to your HttpRequests bycdcarter 1 year, 2 months ago
  4. Serializer factory with Django Rest Framework byjulio 1 year, 9 months ago
  5. Image compression before saving the new model / work with JPG, PNG bySchleidens 1 year, 10 months ago

Comments

Pleaselogin first before commenting.


[8]ページ先頭

©2009-2025 Movatter.jp