Deciding to use @staticmethod, @property, or manager in Django

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

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

链接地址: http://www.djcxy.com/p/55154.html

上一篇: Python中的静态初始化器

下一篇: 决定在Django中使用@staticmethod,@property或manager