1

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.)

Maarten
  • 492
  • 7
  • 14
  • You are using generic relations. What content type (except `Account`) are related with `RelatedUser`? – San4ez May 08 '12 at 17:16
  • For now none, but I have 3 different types of account inheriting from account. I thought this would be a good way to add some flexibility to which user can access different accounts. – Maarten May 08 '12 at 17:21
  • 1
    You should have mentioned this or marked `Account` as abstract model. So I don't have any criticism to your code. Goog luck! P.S. Change `related_user.user.id)` -> `related_user.user_id`. It won't hit db unnecessary time. – San4ez May 08 '12 at 17:32
  • Thanks for that tip, I learn something everyday. I edited my question and my code. On a side note: I tested with one of the models which inherit from account and it works fine. – Maarten May 08 '12 at 17:41

0 Answers0