1

I am developing a GIS based django app in which i am allocating the nearest exam center to a student based on his current location. I have my centre model like this

 class Center(models.Model):
    name = models.CharField(max_length=500)
    city = models.CharField(max_length=100)
    state = models.CharField(max_length=100)
    latitude = models.FloatField()
    longitude = models.FloatField()
    capicity = models.IntegerField()
    examid = models.ForeignKey(Exam)

    class Meta:
        ordering = ['distance']

I am using a function which accept the user's current location and city and then calculate the distance between the current location and all available centres in the given city. And then sort them by distance. But i don't want to change my centre model and use the distance attribute as a temporary attribute for the existing centre model.

Manvendra Singh
  • 586
  • 5
  • 11

1 Answers1

0

While you can assign a model instance an attribute as simply as : instance.attr = value

But, you cannot use it for ordering because django uses order_by to implement this ordering and any such attribute should be an instance of Field class.

You can do this using Django annotate functions. These are functions implemented at database level as explained here.

But, you can always sort using built-in sorted and you can you can use your distance for sorting as explained here

sorted(centeres , key = lambda x : x.distance)

Community
  • 1
  • 1
xssChauhan
  • 2,728
  • 2
  • 25
  • 36