1

I want to create a simple geolocation-based app in Django. I want to keep the location of the user as the last lat/long from where he logged in. For that I have created a Location class. To store additional user data I have a UserProfile class. I want to keep the location column in UserProfile as well.

There are three ways of implementing it that I could think of -- using a @staticmethod, @property, or a manager. And then define a __unicode__ method which would return a list with lat/long of most recent date. Which would be the most apt way of doing it? Following is my model:

class Location(models.Model):
    user = models.ForeignKey(User)
    latitude = models.CharField(max_length=10)
    longitude = models.CharField(max_length=10)
    date = models.DateTimeField(auto_now_add = True)


class UserProfile(models.Model):
    user = models.OneToOneField(User)
    location = the_last_login_location
    rating = models.IntegerField()
Ghopper21
  • 10,287
  • 10
  • 63
  • 92
user993563
  • 18,601
  • 10
  • 42
  • 55

1 Answers1

3

I'd use a property:

class Location(models.Model):
    user = models.ForeignKey(User, related_name="locations")
    latitude = models.CharField(max_length=10)
    longitude = models.CharField(max_length=10)
    date = models.DateTimeField(auto_now_add = True)

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    rating = models.IntegerField()

    @property
    def last_location(self):
        return self.locations.latest("date")
        # Alternatively: return self.objects.all().order_by("-date")[0]

Note the related_name I've added to the user field in the Location model - it makes reverse lookups a little cleaner and easier to read

Edit: I changed the query to use latest()

Timmy O'Mahony
  • 53,000
  • 18
  • 155
  • 177
  • could you please explain, why you would *not* use @staticmethod or manager? – user993563 Aug 06 '12 at 19:19
  • 1
    A manager (which is a feature of Django, not python) is usually meant to operate upon an entire table, not a single row, while a model's methods or properties operate on that particular row. A property makes sense here as you are looking for a particular users last location, not a list of all users latest locations (or something similar). – Timmy O'Mahony Aug 06 '12 at 19:28
  • A static method (which is a feature of Python and programming in general) aren't callable on instances of the class (although they could accept instance of the class) and therefore don't have access to `self` etc. They are used for perform generic operations related to the class, but not necessarily related to the instance. You'll get better definitions on [Wikipedia](http://en.wikipedia.org/wiki/Static_method#Static_methods) or here on [SO](http://stackoverflow.com/questions/735975/static-methods-in-python) – Timmy O'Mahony Aug 06 '12 at 19:34