简体   繁体   中英

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

Querying through the attachments linked to my post yields an empty queryset and i'm not totally sure why. Its probably something stupid but through the admin I can view all the attachments (files) linked to a post. Not sure how the admin is querying or whether I am querying wrong

documentation on many to many fields: https://docs.djangoproject.com/en/3.0/topics/db/examples/many_to_many/

Post links to Attachment through a manytomany field

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')
    ...

Gets all the files from UploadForm, creates an attachment object and adds it to the post

Pic of admin: pic of admin

Testing it out in the 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 []>

# Making a new post through the shell works

>>> 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>]>

Edit: Tried querying the attachment from my template,

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

No surprises here, the only one showing is the one made in the shell

EDIT: Not trying to make this any longer but I just realized my posts were not adding attachments and instead the admin was showing ALL the attachments that you could choose from.

After reading the docs a couple times I realized that storing the action of saving an attachment in the views as 'done' was stupid.

Instead save the upload

upload.save()

then add the upload

p.files.add(upload)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM