[Fixed]-Groups per object using Django and django-guardian object permissions

3👍

Unfortunately there is no way of getting around the unique requirement, that is because this field is used as the id:
https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.unique

Your options are the following:

1) Mocking the model.

You would basically just create a new Group model that doesn’t have the unique requirement. The downside here is that you’d need to use it everywhere, so if this requires updating 3rd party apps, it might not be worth it.

2) make the name you unique. (As you did)

Make sure that you document your convention well, so that all future coders will know what they are looking at.Something like “company name”#”group name” could make more intuitive sense than an id. If the a hash might appear in either then use a more certain delimiter (“__” is a relatively common way of connecting related concepts in django, I might go for this).

I would recommend that you add the following to make it easy for you to access the name.

def get_name(self):
    # Explain how you get the group name from your uniqueified name
    return self.name.split('#')[1] 

Group.add_to_class('get_name', get_name)

When you access your group’s name in your app, just do:

my_group.get_name()

You might also want to put the generating the uniqueified name into an overridden version of the save(). This would give you nicer split between model and view…

Leave a comment