【问题标题】:users to own ther data in django用户在 django 中拥有数据
【发布时间】:2020-12-15 22:30:41
【问题描述】:

我希望用户拥有他们的数据,但这是我不断遇到的错误 " 无法将关键字 'merchant' 解析为字段。选项有:date_added、id、order、order_id、product、product_id、quantity"

models.py

class Merchant(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True)

class Product(models.Model):
   merchant=models.ForeignKey(Merchant, on_delete=models.CASCADE)

class OrderItem(models.Model):
    product=models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)

views.py

def users_homepage(request):
    itemsordered=OrderItem.objects.filter(merchant=request.user.merchant).order_by('date_added')

先谢谢了。

【问题讨论】:

    标签: python python-3.x django django-models django-views


    【解决方案1】:

    OrderItem 没有 merchant 字段,因此您不能对此进行过滤,或者至少不能直接过滤。您可以通过两个连续的下划线 (__) 来“查看”关系:

    def users_homepage(request):
        itemsordered=OrderItem.objects.filter(
            product__merchant__user=request.user
        ).order_by('date_added')
        # …

    注意:通常使用settings.AUTH_USER_MODEL [Django-doc] 引用用户模型比直接使用User model [Django-doc] 更好。更多信息可以查看referencing the User model section of the documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-28
      • 2020-08-02
      • 1970-01-01
      • 2018-01-17
      • 2020-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多