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

What is the best way to save this relation in Django?

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

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

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

我们有这些过滤器的值:4GB、8GB、AMD、Intel、0-9999、10000+、棕色、黑色(人们不能只输入自己的值,他们必须 select列表)

示例 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'))

但是如何 link 它在 Django 中正确地过滤和过滤值?我可以创建两个 Many2Many 关系,但它会创建 3 个数据库。但是,它只需要两个:

项目:

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

item-filter-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 和黑色。

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

您可以 customize the many-to-many table 匹配您建议的 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)

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