views:

60

answers:

1

I'm looking to provide super-user access to entities belonging to a specific country.

eg. Swedish SU can only admin Swedish entities, etc...

However, I'm new to django (taking over an old system) and I need a lifeline.

I'd like to be able to specify a relationship table.

I've already added a userprofile and with that I have a new field called super_user_country_link = models.ForeignKey(SuperUserToCountry, blank=True, null=True)

and then underneath a new class

class SuperUserToCountry(models.Model):
    user = models.ForeignKey(User)
    country = models.ForeignKey(Country) 

I plan to run script then to add an entry for each superuser and give them a link to country 0 (ie, no country => total su access). I can then remove these entries as I start to put country-specific entries in So later I can call(using houses as an example):

if user.is_superuser:
    if user.get_profile().super_user_county_link.country == 0:
        #show house detail...
    elsif user.get_profile().super_user_county_link.country == 0
        #show house detail...
    else
        pass

So looking at it, this should mean that I can list multiple countries against a single user, right? Maybe I'm over-thinking it, but does this look correct?

I'm coming from a php background, so I'm just slighty dubious over how correct this is...

+1  A: 

Correct me if I am wrong. It seems to me that you are trying to establish an many to many relationship between UserProfile and Country. If so the best way to go about it would be to use a ManyToManyField. Something like this:

class UserProfile(models.Model):
    countries = models.ManyToManyField(Country)

You can leave it at that without requiring a separate model (SuperUserToCountry) as long as you are not storing any other information as part of this relationship. If in case you do plan to store other info, there is a way for that too.

The conditions blank = True and null = True are not needed here. If no countries are associated with an user profile then the countries will return an empty lost (i.e. an_instance.countries.all() will be empty).

When you start adding countries you can do something like this:

profile = User.get_profile()
denmark = Country.objects.get(name = 'Denmark')
russia  = Country.objects.get(name = 'Russia')

if denmark in profile.countries.all():
    print "Something is rotten in the state of Denmark"
elsif russia in profile.countries.all():
    print "In Soviet Russia, profiles have countries!"

The above conditions can most likely be expressed more precisely based on your specific need. Incidentally you'll add a country to an user's profile like this:

profile = User.get_profile()
denmark = Country.objects.get(name = 'Denmark')
profile.countries.add(denmark)
Manoj Govindan
Perfect, thank you!
Once_functional