【问题标题】:Django _set.all() filter in QuerySetQuerySet 中的 Django _set.all() 过滤器
【发布时间】:2021-06-16 20:29:46
【问题描述】:

我有数据库,我想从查询集中提取特定用户的特定数据。现在我有了这个

查看

def index(request):
    customerByName = Customer.objects.get(name='pablo')
    shopListById = ShopList.objects.get(transaction_id=1)
    shpoListSpecific = customerByName.shoplist_set.all()
    specificProducts = shopListById.shoplistproduct_set.all()

    context = {'customerByName':customerByName, 'shpoListSpecific':shpoListSpecific, 'shopListById':shopListById,
     'specificProducts': specificProducts}
    return render(request, 'QuickShopperApp/home.html', context)

模型

class Customer(models.Model):
    user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
    name = models.CharField(max_length=200, null=True, blank=True)
    email = models.CharField(max_length=200, null=True, blank=True)
    device = models.CharField(max_length=200, null=True, blank=True)

    def __str__(self):
        if self.name:
            name = self.name
        else:
            name = self.device
        return str(name)

class Product(models.Model):
    name = models.CharField(max_length=200, null=True)

    def __str__(self):
        return self.name


class ShopList(models.Model): # cart
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
    #product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    date_ordered = models.DateTimeField(auto_now_add=True)
    complete = models.BooleanField(default=False)
    transaction_id = models.CharField(max_length=100, null=True)

    def __str__(self):
        return str(self.id)

class ShopListProduct(models.Model): # each ShopList will have multiple ShopListProduct
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    shopList = models.ForeignKey(ShopList, on_delete=models.SET_NULL, null=True) #shoplistitem.shoplist
    quantity = models.IntegerField(default=0, null=True, blank=True)
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.product)

template.html

<h3>specificProducts: {{specificProducts}}</h3>

在我这边,我看到了特定客户的物品。

具体产品:, , ]>

我怎样才能只得到苹果、黄瓜、黄瓜?

【问题讨论】:

    标签: python django database sqlite django-queryset


    【解决方案1】:

    试试这个

    'specificProducts': specificProducts.values_list('product__name')
    
    or
    
    'specificProducts': list(specificProducts.values_list('product__name', flat=True))
    

    https://docs.djangoproject.com/en/3.1/ref/models/querysets/#values-list

    【讨论】:

    • 谢谢你的回答 Mate,现在我有了这个: 如果我做 forloop 我有这个: ('Apple',) ('Cucumber',) ('Cucumber',) 我只想要原始值,例如:Apple Cucumber Cucumber
    猜你喜欢
    • 2014-07-13
    • 2013-09-08
    • 2018-10-09
    • 2018-05-04
    • 2011-03-04
    • 2021-05-13
    • 2016-03-22
    • 2023-03-09
    • 2016-07-21
    相关资源
    最近更新 更多