Wessi Wessi - 4 months ago 13
Python Question

Django self-referential class for most similar car

Let's say I have a class

Car
with a number of fields describing its features. I call and display these features in my html using
{{ object.price }}
etc.

With a nearest neighbor algorithm I have calculated a list of most similar cars for each car and would like to be able to display features of for example the five most similar cars.
Want kind of field should I use for
most_similar_cars
in my class? Please note that the relationship is not symmetric. I.e. while car B might be the nearest neighbor of car A, car A is not necessarily the nearest neighbor of car B. I also need to be able to differentiate between the most similar, second most similar, third most etc.

models.py


from django.db import models

# Create your models here.

class Car(models.Model):
"""A model of a bureau."""
car_model = models.CharField(max_length = 50)
price = models.IntegerField(default=1)
most_similar = ?

def __str__(self):
return self.car_model


I really hope someone can help. Thank you co much.

Answer

You probably want asymmetrycal M2M with custom relation model for ordering nearest cars. In your case:

class Car(models.Model):
    """A model of a bureau."""
    car_model = models.CharField(max_length = 50)
    price = models.IntegerField(default=1)
    most_similar = models.ManyToManyField('self', symmetrical=False, through='CarRelation')

    def __str__(self):
        return self.car_model


class CarRelation(models.Model):
    car = models.ForeignKey(Car)
    close_car = models.ForeignKey(Car, related_name='nearest_cars')
    order = models.PositiveIntegerField()

Then you can add relations like this:

a = Car.objects.create(car_model='A')
b = Car.objects.create(car_model='B')
relation = CarRelation.objects.create(car=a, close_car=b, order=1)

More info in Django docs: https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.ManyToManyField.symmetrical