python - 无法查询 "user": Must be "Model" instance

标签 python django django-filter

我正在尝试在我的私有(private)用户上过滤用户以进行用户聊天,我正在使用模型 (User) 获取 buyer 的用户名和卖家的用户名与另一个模型(Profile)。

问题是我不明白如何解决这个问题以及它为什么会发生:

ValueError: Cannot query "user_39": Must be "Profile" instance.

在我看来:

uc = userComment.objects.all().first()
users = userComment.objects.filter(Q(buyer=uc.buyer) | Q(seller=uc.seller)) #error occurs with this line

pdb.set_trace()

(Pdb) uc.seller
<Profile: user_39>
(Pdb) uc.buyer
<User: user_4>

这是我的两个模型。

class Profile(models.Model):
    name = models.CharField(max_length=120)
    user = models.OneToOneField(User, null=True, blank=True)

class userComment(models.Model):
    buyer = models.ForeignKey(User, related_name="buyer", null=True)
    seller = models.ForeignKey(Profile, related_name="seller", null=True)
    sent_at = models.DateTimeField(auto_now_add=True)
    comment = models.TextField(max_length=255, null=True)

在我的模型上,我不想将 userComment.seller 更改为 ForeignKey(User, ...)

我该如何解决这个问题?


要求的完整代码:

views.py

def addComment(request, gig_id):
    gig = Gig.objects.get(id=gig_id)
    uc = userComment.objects.all().first()
    users = userComment.objects.filter(Q(Q(buyer=uc.buyer) & Q(seller=uc.seller)) | Q(Q(buyer=uc.seller) & Q(seller=uc.buyer))).order_by('sent_at')

    if request.method == 'POST':
        form = userCommentForm(request.POST, request.FILES)
        if form.is_valid():
            form.save(buyer=request.user)
            return HttpResponseRedirect('../' + str(gig.id))
    ...

表单.py

class userCommentForm(forms.Form):
    seller = CommaSeparatedUserField(label=_(u"seller"))
    comment = forms.CharField(label=_(u"comment"), widget=forms.Textarea())

    def save(self, buyer):
        sellers = self.cleaned_data['seller']
        comment = self.cleaned_data['comment']
        message_list = []

        for seller in sellers:
            sl = Profile.objects.get(user=seller) #Connection made here.
            msg = userComment(buyer=buyer, seller=sl, comment=comment,)
            ...
        ...

PDB调试

(Pdb) uc = userComment.objects.all().first()
(Pdb) print('Seller class: %s' % uc.seller.__class__.__name__)
Seller class: Profile
(Pdb) users = userComment.objects.filter(buyer_id=uc.buyer_id)
(Pdb) print(users.count())
3
(Pdb) users = userComment.objects.filter(seller_id=uc.seller_id)
(Pdb) print(users.count())
4
(Pdb) users = userComment.objects.filter(Q(seller_id=uc.seller_id) | Q(buyer_id=uc.buyer_id))
(Pdb) print(users.count())
4
(Pdb) users = userComment.objects.filter(buyer=uc.buyer)
(Pdb) print(users.count())
3
(Pdb) users = userComment.objects.filter(seller=uc.seller)

最佳答案

在您的模型 userComment 中,您有 seller 作为 ForeignKeyProfile,但听起来您想要它在 User 上:

class userComment(models.Model):
    buyer = models.ForeignKey(User, related_name="buyer", null=True)
    seller = models.ForeignKey(User, related_name="seller", null=True)

编辑:

抱歉,我回答得太快了,你的错误基本上是这样说的:你在 buyer 字段和 seller 上都使用条件 uc.buyer 进行了查询字段,但是 seller 被定义为 Profile 的外键,因此您不能使用用户对象来查询 Profile 字段。也许你想要这个?

users = userComment.objects.filter(Q(buyer=uc.buyer) | Q(seller=uc.seller))

重新编辑:

应该使用User作为userComment的外键seller,因为这就是关系的样子,而您使用关系可以获得您需要的所有信息。使用 User 作为外键,您可以做任何事情:

# get a user's profile
profile = user.profile
# query with profile's information on `userComment`
userComment.objects.filter(buyer__profile__name='Tom')

检查 how to query across relationships 上的 django 文档.

关于python - 无法查询 "user": Must be "Model" instance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41554903/

相关文章:

django - 在 admin.py 中为搜索字段添加 help_text

python - 有人能解释一下 django 中 "etag"有什么用吗?

python - Django 按条件过滤

python - 我想将元组值添加到元组,如果该元组[0 :2] is repeated as shown below:

python - 根据列值加入 Pandas 数据框

python - 添加到帖子 : Page not found (404) 的评论

django - 如何从 django-filters.FilterList 获取请求参数

django - 如何使用Django通用 View 过滤表?

python - 使用列的长度过滤 DataFrame

python函数参数搞砸了