在Django中保存这种关系的最佳方法是什么?

时间:2015-04-13 13:54:12

标签: python django m2m

让我们假设我们正在创建一个网站,人们可以向其他人出售任何东西。

例如,我们有两个类别:计算机和汽车

我们有一些类别的过滤器:内存,CPU,里程,颜色

我们对这些过滤器有价值:4GB,8GB,AMD,Intel,0-9999,10000 +,Brown,Black(人们不能只输入自己的值,他们必须从列表中选择它们)

示例Django代码:

class Category(models.Model):
    parent = models.ForeignKey('self', null=True, blank=True)
    name = models.CharField(_('Name'), max_length=30)


class Filter(models.Model):
    categories = models.ManyToManyField(Category, db_index=True)
    name = models.CharField(_('Name'), max_length=30)


class FilterValue(models.Model):
    filter = models.ForeignKey(Filter, db_index=True)
    value = models.CharField(_('Filter value'), max_length=30)

因此,过滤器与类别相关,过滤器值与过滤器相关。现在我们有了表格:

类:

id | name
------------------
 1 | Computers
 2 | Cars

过滤器:

id | name
------------------
 1 | CPU
 2 | Memory
 3 | Mileage
 4 | Color

类别的过滤器:

id | category_id | filter_id
-----------------------------
 1 |           1 |         1
 2 |           1 |         2
 3 |           2 |         3
 4 |           2 |         4

filter_values:

id | filter_id | name
-----------------------------
 1 |         1 | Intel
 2 |         1 | AMD
 3 |         2 | 4GB
 4 |         2 | 8GB
 5 |         3 | 0-9999
 6 |         3 | 10000+
 7 |         4 | Brown
 8 |         4 | Black

现在问题出现了 - 我应该如何制作Item模型? 示例代码:

class Item(models.Model):
    category = models.ForeignKey(Category, db_index=True)
    name = models.CharField(_('Name'), max_length=30)
    price = models.IntegerField(_('Price'))

但是如何将它链接到过滤器并在Django中正确过滤值?我可以创建两个Many2Many关系,但它会创建 3个数据库。但是,它只需要两个

项:

id | category_id | name
------------------------------
 1 |           1 | My computer
 2 |           2 | My car

项滤波器-FILTER_VALUE:

id | item_id | filter_id | filter_value_id
------------------------------------------
 1 |       1 |         1 |               2
 2 |       1 |         2 |               3
 3 |       2 |         3 |               5
 4 |       2 |         4 |               8

所以现在在DB中有两个项目:我的计算机配有AMD CPU和4GB内存,我的车里程为0-9999,黑色。

实现这种逻辑的正确方法是哪种方式?

1 个答案:

答案 0 :(得分:2)

您可以customize the many-to-many table匹配您建议的表格。在您的示例中,它可能如下所示:

class Item(models.Model):
    category = models.ForeignKey(Category, db_index=True)
    name = models.CharField(_('Name'), max_length=30)
    price = models.IntegerField(_('Price'))
    filters = models.ManyToManyField(Filter, through='ItemFilter')

class ItemFilter(models.Model):
    item = models.ForeignKey(Item)
    filter = models.ForeignKey(Filter)
    value = models.ForeignKey(FilterValue)

请注意有关如何访问直通模型字段以及如何更改相关经理的文档。

相关问题