在Django模型中自定义相关字段,指定通过

时间:2017-03-26 16:25:13

标签: python django foreign-key-relationship django-custom-manager

在我的Django项目中,我有一个看起来像这样的产品模型:

class Manufacturer(models.Model):
    name = models.CharField(max_length=100)

class Product(models.Model):
    manufacturer = models.ForeignKey('Manufacturer')
    # .favorite_set: ManyToOne relation coming from the
    # 'Favorite' class (shown a couple of lines below)

我的网站用户可以将某些产品标记为收藏。为了提供这个功能,我有一个看起来像这样的Django模型:

class Favorite(models.Model):
    user = models.ForeignKey(User)
    product = models.ForeignKey('Product')

    class Meta:
        unique_together = ('user', 'product',)

在该模型中,.product ForeignKey在名为Product的{​​{1}}模型中创建反向关系。这一切都很好,很有用:当我收到用户的HTTP请求以检索产品时,我可以通过这样做轻松地确定它是否被特定用户收藏:

favorite_set

现在,我有另一个严重非规范化的模型(SQL非规范化,即我想用于快速文本搜索)。

这个模型"假装"成为一个产品,但包括通过"常规"产品与模型本身的FK关系。像这样:

product = Product.objects.get(id='whatever_id')
is_favorited = bool(product.favorite_set.filter(user=self.user).count() == 1)
# or probably:
#   is_favorited = product.favorite_set.filter(user=self.user).exists()
# 

这个类有自己的class ProductSearch(models.Model): product = models.OneToOneField('Product', on_delete=models.CASCADE, related_name='searcher') product_name = models.CharField(max_length=100) manufacturer_name = models.CharField(max_length=100) 字段(因为它是Django模型),正如你在上面看到的那样,它与产品有一个id的关系。这个OneToOne条目链接到一个且只有一个ProductSearch

感谢这个模型,如果我想搜索制造商是" Ford" (例如)的产品,我不需要加入{{1带有Product表格的表格。我可以直接在Product中进行查找并节省几毫秒。

由于Manufacturer旨在与ProductSearch兼容,我还尝试对发生的ProductSearch进行建模"自然"在我的Product课程中加入此favorite_set模型。

出现困难的地方:我不知道怎么做: - )

我理想情况下会有:

Product

但我还没能做到。

我曾试图"滥用" ProductSearch就像这样:

class ProductSearch(models.Model):
    product = models.OneToOneField('Product', 
                                   on_delete=models.CASCADE,
                                   related_name='searcher')
    manufacturer_name = models.CharField(max_length=100)
    #
    # Couldn't find anything to do the following:
    product_favorite_set = models.ManyToOneField('Favorite',
                                                 through_fields=('product',))

但是这会在系统检查中产生错误:

ManyToManyField

我想我可以将class ProductSearch(BaseModel): product = models.OneToOneField('Product', on_delete=models.CASCADE, related_name='searcher') product_name = models.CharField(max_length=100) manufacturer_name = models.CharField(max_length=100) product_favorite_set = models.ManyToManyField('Favorite', related_name='+', through='Favorite', through_fields=['product'] ) 设为Python api.Favorite: (fields.E336) The model is used as an intermediate model by 'api.ProductSearch.product_favorite_set', but it does not have a foreign key to 'ProductSearch' or 'Favorite'. api.ProductSearch.product_favorite_set: (fields.E339) 'Favorite.product' is not a foreign key to 'ProductSearch'. ,然后在其中执行自定义查询,如:

product_favorite_set

但我想知道我是否可以使用" pure" Django工具(只有出于好奇)

非常感谢任何帮助。提前谢谢。

0 个答案:

没有答案