简体   繁体   English

大多数类似汽车的Django自引用类

[英]Django self-referential class for most similar car

Let's say I have a class Car with a number of fields describing its features. 假设我有一个Car类,其中包含许多描述其功能的字段。 I call and display these features in my html using {{ object.price }} etc. 我使用{{ object.price }}等在html中调用并显示这些功能。

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? 想要在我的课程中用于most_similar_cars的字段类型吗? Please note that the relationship is not symmetric. 请注意,这种关系不是对称的。 Ie 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. 也就是说,虽然汽车B可能是汽车A的最近邻居,但汽车A不一定是汽车B的最近邻居。我还需要能够区分最相似,第二相似,第三等。

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. 非常感谢您。

You probably want asymmetrycal M2M with custom relation model for ordering nearest cars. 您可能希望使用具有自定义关系模型的不对称M2M来订购最近的汽车。 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()

    class Meta:
        ordering = ('order',)

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 Django docs中的更多信息: https : //docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.ManyToManyField.symmetrical

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM