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

Querying many to many field in django yields an empty query set

通过链接到我的 post 的附件进行查询会产生一个空的查询集,我不完全确定为什么。 它可能有些愚蠢,但通过管理员我可以查看链接到 post 的所有附件(文件)。不知道管理员是怎么查询的还是我查询错了

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

Post 通过多对多字段链接到附件

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 获取所有文件,创建附件对象并将其添加到 post

管理员图片: pic of admin

正在 shell 中进行测试:

>>> 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作品制作新的post

>>> 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 %}

这里没有惊喜,唯一展示的是 shell

中制作的那个

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

看了几次文档后,我意识到在视图中将保存附件的操作存储为 'done' 是愚蠢的。

改为保存上传

upload.save()

然后添加上传

p.files.add(upload)

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