使用Django searchvector返回重复的对象

2024-04-16 07:11:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码:

vector = SearchVector('product__name', weight='A') + SearchVector('product__tags__name', weight='B')
logger.info("busqueda libre, query %s" % query)
data = StockItem.objects.annotate(search=vector).filter(search=query, product__cover__isnull=False,
                                                                available=True).order_by(sort)

并且在查询中返回重复的对象,我不能使用distinct,因为顺序是由用户给定的,所以我可以使用什么来解决这个问题?你知道吗

查询中使用的模型:

class StockItem(models.Model):
    product = models.ForeignKey(Product, null=False, related_name='items', on_delete=models.CASCADE, db_index=True)
    available = models.BooleanField(default=True)
    retailer = models.ForeignKey(Retailer, null=False, related_name='items', db_index=True)
    sku = models.CharField(max_length=100, db_index=True, unique=True)
    price = models.DecimalField(decimal_places=2, null=True, max_digits=6, blank=True)
    cost_price = models.DecimalField(decimal_places=2, null=True, max_digits=6, blank=True)
    promo = models.ForeignKey(PromoItem, null=True, blank=True)
    updated_at = models.DateTimeField(auto_now=True, db_index=True)
    margin = models.DecimalField(decimal_places=2, max_digits=4, null=True, blank=True)


class Product(models.Model):
    UNITS = (
    ('LB', _(u'lb')),
    ('KG', _(u'kg')),
    ('G', _(u'g')),
    ('ML', _(u'ml')),
    ('L', _(u'l')),
    ('U', _(u'un')),
    ('ATADO', _(u'atado'))
    )

    name = models.CharField(max_length=100, db_index=True)
    ean = models.CharField(max_length=13, db_index=True, unique=True)
    quantity = models.DecimalField(null=True, decimal_places=2, max_digits=10)
    unit = models.CharField(max_length=6, choices=UNITS, null=True, db_index=True)
    likes = models.PositiveSmallIntegerField(default=0)
    brand = models.ForeignKey(Brand, null=True, blank=True, related_name='products', db_index=True)
    tags = models.ManyToManyField(Tag, blank=True, db_index=True)
    category = models.ManyToManyField(Category, blank=True, related_name='products_category', db_index=True)
    subcategory = models.ManyToManyField(SubCategory, blank=True, related_name='products_subcategory')
    tax = models.ManyToManyField(Tax, related_name="taxes", blank=True)
    description = HTMLField(blank=True, null=True, max_length=15000)
    updated_at = models.DateTimeField(auto_now=True, db_index=True)
    bulk = models.BooleanField(default=False)
    unit_stock = models.BooleanField(default=False)

class Tag(models.Model):
    name = models.CharField(max_length=100, db_index=True)

Tags: namefalsetruedefaultdbindexmodelsproduct