views:

47

answers:

1

Hi guys,

I'm writing a Project in Django where I've 5 kind of groups of Users:

  • Group1
  • Group2
  • ...

Then I've a Model, Item which has many relation with users, the Item has one Owner (a User in Group1), a Customer (an User in Group2) and many RelatedUser (Users in Group3).

I'm wondering which is the correct way to write this relations. I'd love to write something like:

class Item(models.Model):
    owner = models.ForeignKey(Owner)
    customer = models.ForeignKey(Customer)
    users = models.ManyToManyField(RelatedUser)

Having defined in some way Owner, Customer and RelatedUser classes.

I do not know how to achieve this. I do not want to use model inheritance, because I just want a table User. Even Managers does not seems to help me. Actually I'm using something like this:

try:
    customer = models.ForeignKey(User,
                              related_name='cust',
                              limit_choices_to = {'groups__in': [Group.objects.get(name = 'customers')]})
except:
    customer = models.ForeignKey(User,
                              related_name='cust')

Mostly because when starting form an empty database Group 'customers' does not exists and errors are raised.

Which is the right way to afford this?

Thanks in advance

A: 

You could define separate models for each user type - each with a ForiegnKey to User. The upside is simplicity, but the down side is that this approach adds multiple tables, and isn't particularly extensible if you need to add more groups later.

Another option is to define a Groups model, which stores the different types of groups available, and has a ManyToMany relationship to User (assuming one user can be in multiple groups).

You can get around the problem of no groups being defined when starting from a new database by creating a fixture for the Groups model . A fixture is a text file (default is JSON format) that defines a set of data that can be easily loaded into the DB, either automatically or manually. Fixtures can be easily created from existing data with the dumpdata management command.

If you wish a fixture to be loaded automatically (when you run syncdb), create a fixtures directory in your app, and name the fixture initial_data. You can also create other fixtures and load them with either the loaddata command, or in your tests by specifying a fixtures list for a particular TestCase

Chris Lawlor
As far as I exeprienced, fixtures does not prevent the error i show before (the try: except:), because the models are parsed before creating models, and when the definition of 'groups_is' is reached it breaks up. I'm actually using the group model carried with django.contrib.auth.
Enrico Carlesso