Populate keywords on save

42 views
Skip to first unread message

Eduardo Rivas

unread,
Sep 13, 2012, 4:53:56 AM9/13/12
to mezzani...@googlegroups.com
I'm trying to populate the keyword field inherited from MetaData with a list of items in a ManyToMany field in my model.

models.py
class Data(Page):
categories = models.ManyToManyField(...)
def save(self, *args, **kwargs):
keywords = ",".join([i.title for i in self.categories.all()])
super(Data, self).save(*args, **kwargs)

This gives the error: 'AssignedKeyword" instance expected. 

Ken Bolton

unread,
Sep 13, 2012, 8:30:35 AM9/13/12
to mezzani...@googlegroups.com
Hi Eduardo,

In `categories = models.ManyToManyField(...)`, what are the args of
the ManyToManyField()? A `Page.keywords` field takes an
`AssignedKeyword` as its value.

The implementation, which should help to clarify this, is here:
https://github.com/stephenmcd/mezzanine/blob/master/mezzanine/generic/models.py#L82-109
https://github.com/stephenmcd/mezzanine/blob/master/mezzanine/generic/fields.py#L136-219

ken

Eduardo Rivas

unread,
Sep 13, 2012, 11:38:16 AM9/13/12
to mezzani...@googlegroups.com
The m2m relationship is set to be made with a Displayable model.

class Data(Page)
categories = models.ManyToManyField("MyCategory")
 #More fields
 
class MyCategory(Displayable):
# No extra fields

Is this the problem? If so, how can I populate the keywords field from a list coming from a m2m relationship?

Ken Bolton

unread,
Sep 13, 2012, 11:56:55 AM9/13/12
to mezzani...@googlegroups.com
The problem is with using `keywords` in your save() method.
`keywords`, which is a field on `Page` (inherited from
`core.models.MetaData`), expects the values passed in to be
`AssignedKeywords`. I think you will need to first create `Keyword`
instances from your `MyCategory.title`s, then pass those into your
save() method.

But this begs a larger question: are Categories really Keywords? It
seems like a duplication of data, and will limit your ability to
filter by Category and Keyword independently, not to mention making
your application more complex than it may need to be.

Hope this helps.

ken

Eduardo Rivas

unread,
Sep 13, 2012, 12:04:39 PM9/13/12
to mezzani...@googlegroups.com
The reason I was trying to do this is to have a more powerful category framework. With this implementation, each Data can have its Categories as meta keywords, and each category (because they will have assigned pages in the public site) can have its own description, publish status, etc; and its related Data instances as meta keywords.

Now of course, this is my effort at using the "keywords" field provided by Mezzanine. An alternate solution would be to render the meta keywords by traversing the m2m relationships in the templates, and adding that to the elements provided by the keywords field.
Reply all
Reply to author
Forward
0 new messages