在Django中查询多对多字段会产生一个空查询集

2024-05-22 18:28:29 发布

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

通过链接到我的帖子的附件进行查询会产生一个空的查询集,我不完全确定原因。 这可能有点愚蠢,但通过管理员我可以查看链接到帖子的所有附件(文件)。不确定管理员是如何查询的,或者我是否查询错了

关于多对多字段的文档:https://docs.djangoproject.com/en/3.0/topics/db/examples/many_to_many/

通过多个字段发布附件链接

Views.py

def UploadView(request):

    if request.method == 'POST':
        post_form = PostForm(request.POST)
        upload_form = UploadForm(request.POST, request.FILES)
        files = request.FILES.getlist('upload')

        if post_form.is_valid() and upload_form.is_valid():
            post_form.instance.author = request.user
            p = post_form.save()
            for f in files:  
                upload = Attachment(upload=f) #create an attachment object for each file
                done = upload.save()  #save it
                p.files.add(done)  #add it to the post object (saved before)

            return redirect('user-dashboard')
    ...

从UploadForm获取所有文件,创建附件对象并将其添加到帖子中

管理员图片: pic of admin

在外壳中进行测试:

>>> from uploadlogic.models import Post, Attachment
>>> p = Post.objects.all().last() 
>>> p.files
>>> p.files.all()
<QuerySet []>
>>> f = Attachment.objects.all()
>>> for i in f:
...     print(i.post_set.all())            
... 
<QuerySet []>
<QuerySet []>
<QuerySet []>
<QuerySet []>
<QuerySet []>
<QuerySet []>
<QuerySet []>

#通过shell制作一篇新帖子很有效

>>> k = Post(headline="",description = "",rank =20,author=CustomUser.objects.first())        
>>> k.save()
>>> k.files.add(Attachment.objects.first())
>>> k.save()
>>> k
<Post:  - 20>
>>> k.files.all()
<QuerySet [<Attachment: 1 - attachement>]>

编辑: 尝试从我的模板中查询附件

{% for attachment in post.files.all%}
    <h1> Attachment included!</h1>
    {% endfor %}

在这里没有什么奇怪的,只有一个显示的是一个在贝壳

编辑:我不再尝试这样做了,但我只是意识到我的帖子没有添加附件,而是管理员显示了你可以选择的所有附件


Tags: formfor附件attachmentobjectsrequestsave管理员
1条回答
网友
1楼 · 发布于 2024-05-22 18:28:29

读了几遍文档后,我意识到将附件保存在视图中的操作存储为“完成”是愚蠢的

而是保存上传

upload.save()

然后添加上传

p.files.add(upload)

hope this helps anyway else trying to do multi file uploads that have a relationship with an object.

相关问题 更多 >

    热门问题