I wanted a simple way of relating multiple users ta an account in Django. I think I found a solution and it seems to be working. I've run into some more elaborate versions of what I am trying now. I was wondering if there were any objections worth considering. For now I am happy I have it working but my experience with Django is still limited so any feedback would be welcome.
The two models below:
class Account(models.Model):
related_users = generic.GenericRelation('RelatedUser')
public = models.BooleanField(default=True)
name = models.CharField(max_length=250)
slug = models.SlugField(max_length=250)
# Other fields....
def __unicode__(self):
return self.name
# Get related user-id's and append them into a list
def get_related_users(self):
users = self.related_users.all()
related = []
for related_user in users:
related.append(related_user.user_id)
return related
class RelatedUser(models.Model):
content_type = models.ForeignKey(ContentType, related_name="user_relation")
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
user = models.ForeignKey(User, null=True, blank=True, related_name='user_relation')
then one of my (partial)views below:
@login_required
def account_edit(request, account_id):
account = get_object_or_404(Account, pk=account_id)
users = account.get_related_users()
if request.user.is_superuser or request.user.id in users:
form = AccountForm(request.POST or None, instance=account)
if form.is_valid():
artist = form.save(commit=False)
artist.save()
return redirect(account_list)
else:
return redirect(account_list)
I Tested this with a couple of users, it does what I want it to do. I was just wondering, is this safe and efficient enough to use in production? (I have a blog running on a home-server but that is about as far as my deployment experience goes.)