Need Help with Many to Many Fields

23 views
Skip to first unread message

Mark Phillips

unread,
Dec 8, 2017, 8:08:17 PM12/8/17
to django users
I have two models - 

class Document(models.Model):
    document_id = models.AutoField(primary_key=True)
    title = models.CharField('title', max_length=200)
    
    class Meta:
        ordering = ['title']

    def __str__(self):
        return "%s" % (self.title)

class Collection(models.Model):
    collection_id = models.AutoField(primary_key=True)
    name = models.CharField('title', max_length=200)
    description = models.TextField('description')
    document = models.ManyToManyField(Document,)

In admin.py, I am trying to show the documents that are in a collection. I have this:

class CollectionAdmin(admin.ModelAdmin):
    filter_horizontal = ('document',)
    list_display = ('name', 'description', 'get_documents')
    
    def get_documents(self, obj):
        documents = Collection.objects.filter(collection_id=obj.collection_id).values('document')
        templist = []
        for doc in documents:
            d = Document.objects.get(document_id=doc['document']).title
            templist.append(d)
        return templist

My question is, I getting the titles of the documents in the collection correctly? Is there some way to get a queryset to look up the Document fields directly, or do I have to make two queries as I am doing?

Thanks!

Mark


Constantine Covtushenko

unread,
Dec 8, 2017, 9:58:10 PM12/8/17
to django...@googlegroups.com
Hi Mark,

Answering on your question I would do in your `get_documents` method:

return obj.document.all().values_list('title', flat=True)

this will get list of all document titles.

But at the same time why do you need get_documents method? How do you use it?
May be it is better to optimize `get_queryset` of CollecionAdmin instead?

Regards,
Constantine C.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAEqej2NmUSH-W2_Fd9WkmPjZzj5krk2Qmw4DyaWBkj5_mj46Kw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.



--
Sincerely yours,
Constantine C

Mark Phillips

unread,
Dec 9, 2017, 12:42:32 AM12/9/17
to django users
The point of the queries is to get information about the underlying Documents in each Collection, and display it in the admin page. For example, title is one attribute, but there are also other that I want to display.

Your idea obj.document.all().values_list('title', flat=True) makes a lot of sense - Thanks! 

Now, a bigger question. Say I have two fields in Documents that I want to display side by side in a table in the Collection admin page. I would have two entries in the list_display:

list_display = ('get_field_1', 'get_field_2', )

and two functions, and each one calls obj.document.all(), which returns a query set of Documents in this particular Collection. 

def get_field_1(self, obj):
    tempstr = ""
    documents = obj.document.all()
    for d in documents:
        tempstr = tempstr + d.field_1
    return tempstr

def get_field_2(self, obj):
    tempstr = ""
    documents = obj.document.all()
    for d in documents:
        tempstr = tempstr + d.field_2
    return tempstr

These two "list of fields" from the Documents are displayed side by side. Will the first entry in the field_1 list always correspond to the first entry in the field_2 list? In other words, I am concerned about the order of the documents returned in the query set obj.document.all(). Will it always be the same?

Perhaps a picture will help (I hope it comes through). Note the ordered lists of file names and thumbnails. I used the code above (with a few modifications) to generate the table. My concern is if the file name in the first list (a field in the Document model) will always correspond to the thumbnail in the second column (another field in the Document model).

Thanks!

Screenshot from 2017-12-08 22:02:58.png

Constantine Covtushenko

unread,
Dec 9, 2017, 10:55:24 AM12/9/17
to django...@googlegroups.com
Hi Mark,

You should not create 2 methods.
Just change that first to be like:

return obj.document.all().values_list('field_1', 'field_2')

With this you will get QuerySet of tuples, like
<QuerySet [(obj1_field_1_value, obj1_field_2_value), ...]>

I believe it should solve your problem.

Also for more references about values_list, check following documentation page:

Regards,
Constantine C.


For more options, visit https://groups.google.com/d/optout.

Mark Phillips

unread,
Dec 9, 2017, 11:15:16 AM12/9/17
to django users
Constantine,

Thanks for the link and update! However, I am not sure how to make two columns in the CollectionsAdmin table without two functions. 

class COllectionAdmin(self, obj):
list_display = 

Mark Phillips

unread,
Dec 9, 2017, 11:17:40 AM12/9/17
to django users
Hit send by accident...

Constantine,

Thanks for the link and update! However, I am not sure how to make two columns in the CollectionsAdmin table without two functions. 

class CollectionAdmin(self, obj):
    list_display = ('get_field_1', 'get_field_2', )

    def get_field_1(self, obj):
        tempstr = ""
        documents = obj.document.all()
        for d in documents:
            tempstr = tempstr + d.field_1
       return tempstr

    def get_field_2(self, obj):
        tempstr = ""
        documents = obj.document.all()
        for d in documents:
           tempstr = tempstr + d.field_2
        return tempstr

Mark

Mark Phillips

unread,
Dec 9, 2017, 11:33:44 AM12/9/17
to django users
should have been 

class CollectionAdmin(admin.ModelAdmin)
in the above post.

Mark

Constantine Covtushenko

unread,
Dec 9, 2017, 1:05:41 PM12/9/17
to django...@googlegroups.com
Hi Marks,

Ok, I would use `prefetch_related` method then.

you should override `get_queryset` with something like that:
def get_queryset(self, request):
return super().get_queryset(request).prefetch_related('document')
> In your model you specified `document` not `documents` that is why I used `document`

With this all related document would be already in memory.
In your methods you can do something like this:

def get_field_1(self, obj):
return ''.join([q.field_1 for q in obj.document.all()])
And use the same approach for second method

Does it make any sense?

Regards,
Constantine C.


For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages