Retrieving metadata from a post, then sorting posts by said metadata in django












1















I have two interconnected models in my blog app; Category and Post. The blog front page displays a list of posts and their corresponding metadata, like it should; fairly standard stuff.



Aside from displaying the posts on the front page, they're also displayed on the individual user's profile page in short form (just the category and the headline).



What I'm interested in doing is sorting all the posts that belong in a category, however the only way I've managed to make it work is something like this:



NEWS
some title
NEWS
another title
PYTHON
another arbitrary title
NEWS
yet another title



I'd like to sort it thusly instead:



NEWS
some title
another title
yet another title
PYTHON
another arbitrary title



Alas, my mind keeps turning into a bowl of spaghetti when I try to come up with a method, so without further ado; how should I go about this bit?
I reckon that there's something off with calling the category from the post's metadata only to try and categorize the posts via the retrieved data, but aside from that, I'm somewhat lost.



Here's the template snippet from user_profile.html:



{% if user.post_set.exists %}
<p>
{% for post in user.post_set.all|dictsortreversed:"date_posted" %}
<span style="margin-right: 5px; padding: 3px 6px; border-radius:12px; color:#FFF; background-color:#FFA826;">{{ post.category }}</span><br/>
<a style="margin-left:3px;" href="{% url 'blog:post-detail' post.slug %}">{{ post.title|truncatechars_html:30 }}</a><br/>
{% endfor %}
</p>
{% endif %}


The models:



class Category(models.Model):
class Meta:
verbose_name = 'category'
verbose_name_plural = 'categories'

name = models.CharField(max_length=30)

def __str__(self):
return self.name


class Post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=60)
category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.CASCADE)
content = RichTextUploadingField(
external_plugin_resources=[(
'youtube',
'/static/ckeditor/ckeditor/plugins/youtube/',
'plugin.js'
)],
blank=True,
null=True,
)
date_posted = models.DateTimeField(default=timezone.now)
updated = models.DateTimeField(auto_now=True)
slug = models.SlugField(max_length=70, blank=True, null=True, help_text='<font color="red">don't. touch. the. slug. field. unless. you. mean. it.</font> (it will auto-generate, don't worry.)')

def __str__(self):
return self.title

def get_absolute_url(self):
return reverse('blog:post-detail', kwargs={'slug': self.slug})


And finally the view which relate to the post_list.html:



class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = '-date_posted'
paginate_by = 6


Should I be doing it in a different manner altogether, I wonder? And if so, what would be considered 'best practice'?



Thank you :)










share|improve this question























  • Hi, is the given solution not working? maybe removing dictsortreversed:"date_posted" from template might help with the answer. Anyways, if it does not work then it would be great what kind behavior are you getting. because it is odd as you have accepted and then unaccepted the solution. Cheers!!

    – ruddra
    Nov 17 '18 at 16:05













  • Yeah, I jumped the gun on accepting the answer, as it seemed like exactly what I'd like to do before trying it out. Sorry about that. I'm currently trying out different variations with the template combined with your advice (ie. omitting the dictsortreversed and adding a for loop for the categories within the post for loop), but still struggling. Ironically I managed to do the exact opposite of what I intended, i.e NEWS NEWS NEWS some arbitrary title another title PYTHON PYTHON PYTHON yet another title, the titles repeating for as many times as there are available posts.

    – Puto Miké
    Nov 17 '18 at 17:32






  • 1





    I will reaccept once I sort it out; was too embarrased to ask again. Just gimme a minute to sort it please.

    – Puto Miké
    Nov 17 '18 at 17:39











  • Sure, go ahead.

    – ruddra
    Nov 17 '18 at 17:42
















1















I have two interconnected models in my blog app; Category and Post. The blog front page displays a list of posts and their corresponding metadata, like it should; fairly standard stuff.



Aside from displaying the posts on the front page, they're also displayed on the individual user's profile page in short form (just the category and the headline).



What I'm interested in doing is sorting all the posts that belong in a category, however the only way I've managed to make it work is something like this:



NEWS
some title
NEWS
another title
PYTHON
another arbitrary title
NEWS
yet another title



I'd like to sort it thusly instead:



NEWS
some title
another title
yet another title
PYTHON
another arbitrary title



Alas, my mind keeps turning into a bowl of spaghetti when I try to come up with a method, so without further ado; how should I go about this bit?
I reckon that there's something off with calling the category from the post's metadata only to try and categorize the posts via the retrieved data, but aside from that, I'm somewhat lost.



Here's the template snippet from user_profile.html:



{% if user.post_set.exists %}
<p>
{% for post in user.post_set.all|dictsortreversed:"date_posted" %}
<span style="margin-right: 5px; padding: 3px 6px; border-radius:12px; color:#FFF; background-color:#FFA826;">{{ post.category }}</span><br/>
<a style="margin-left:3px;" href="{% url 'blog:post-detail' post.slug %}">{{ post.title|truncatechars_html:30 }}</a><br/>
{% endfor %}
</p>
{% endif %}


The models:



class Category(models.Model):
class Meta:
verbose_name = 'category'
verbose_name_plural = 'categories'

name = models.CharField(max_length=30)

def __str__(self):
return self.name


class Post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=60)
category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.CASCADE)
content = RichTextUploadingField(
external_plugin_resources=[(
'youtube',
'/static/ckeditor/ckeditor/plugins/youtube/',
'plugin.js'
)],
blank=True,
null=True,
)
date_posted = models.DateTimeField(default=timezone.now)
updated = models.DateTimeField(auto_now=True)
slug = models.SlugField(max_length=70, blank=True, null=True, help_text='<font color="red">don't. touch. the. slug. field. unless. you. mean. it.</font> (it will auto-generate, don't worry.)')

def __str__(self):
return self.title

def get_absolute_url(self):
return reverse('blog:post-detail', kwargs={'slug': self.slug})


And finally the view which relate to the post_list.html:



class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = '-date_posted'
paginate_by = 6


Should I be doing it in a different manner altogether, I wonder? And if so, what would be considered 'best practice'?



Thank you :)










share|improve this question























  • Hi, is the given solution not working? maybe removing dictsortreversed:"date_posted" from template might help with the answer. Anyways, if it does not work then it would be great what kind behavior are you getting. because it is odd as you have accepted and then unaccepted the solution. Cheers!!

    – ruddra
    Nov 17 '18 at 16:05













  • Yeah, I jumped the gun on accepting the answer, as it seemed like exactly what I'd like to do before trying it out. Sorry about that. I'm currently trying out different variations with the template combined with your advice (ie. omitting the dictsortreversed and adding a for loop for the categories within the post for loop), but still struggling. Ironically I managed to do the exact opposite of what I intended, i.e NEWS NEWS NEWS some arbitrary title another title PYTHON PYTHON PYTHON yet another title, the titles repeating for as many times as there are available posts.

    – Puto Miké
    Nov 17 '18 at 17:32






  • 1





    I will reaccept once I sort it out; was too embarrased to ask again. Just gimme a minute to sort it please.

    – Puto Miké
    Nov 17 '18 at 17:39











  • Sure, go ahead.

    – ruddra
    Nov 17 '18 at 17:42














1












1








1








I have two interconnected models in my blog app; Category and Post. The blog front page displays a list of posts and their corresponding metadata, like it should; fairly standard stuff.



Aside from displaying the posts on the front page, they're also displayed on the individual user's profile page in short form (just the category and the headline).



What I'm interested in doing is sorting all the posts that belong in a category, however the only way I've managed to make it work is something like this:



NEWS
some title
NEWS
another title
PYTHON
another arbitrary title
NEWS
yet another title



I'd like to sort it thusly instead:



NEWS
some title
another title
yet another title
PYTHON
another arbitrary title



Alas, my mind keeps turning into a bowl of spaghetti when I try to come up with a method, so without further ado; how should I go about this bit?
I reckon that there's something off with calling the category from the post's metadata only to try and categorize the posts via the retrieved data, but aside from that, I'm somewhat lost.



Here's the template snippet from user_profile.html:



{% if user.post_set.exists %}
<p>
{% for post in user.post_set.all|dictsortreversed:"date_posted" %}
<span style="margin-right: 5px; padding: 3px 6px; border-radius:12px; color:#FFF; background-color:#FFA826;">{{ post.category }}</span><br/>
<a style="margin-left:3px;" href="{% url 'blog:post-detail' post.slug %}">{{ post.title|truncatechars_html:30 }}</a><br/>
{% endfor %}
</p>
{% endif %}


The models:



class Category(models.Model):
class Meta:
verbose_name = 'category'
verbose_name_plural = 'categories'

name = models.CharField(max_length=30)

def __str__(self):
return self.name


class Post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=60)
category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.CASCADE)
content = RichTextUploadingField(
external_plugin_resources=[(
'youtube',
'/static/ckeditor/ckeditor/plugins/youtube/',
'plugin.js'
)],
blank=True,
null=True,
)
date_posted = models.DateTimeField(default=timezone.now)
updated = models.DateTimeField(auto_now=True)
slug = models.SlugField(max_length=70, blank=True, null=True, help_text='<font color="red">don't. touch. the. slug. field. unless. you. mean. it.</font> (it will auto-generate, don't worry.)')

def __str__(self):
return self.title

def get_absolute_url(self):
return reverse('blog:post-detail', kwargs={'slug': self.slug})


And finally the view which relate to the post_list.html:



class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = '-date_posted'
paginate_by = 6


Should I be doing it in a different manner altogether, I wonder? And if so, what would be considered 'best practice'?



Thank you :)










share|improve this question














I have two interconnected models in my blog app; Category and Post. The blog front page displays a list of posts and their corresponding metadata, like it should; fairly standard stuff.



Aside from displaying the posts on the front page, they're also displayed on the individual user's profile page in short form (just the category and the headline).



What I'm interested in doing is sorting all the posts that belong in a category, however the only way I've managed to make it work is something like this:



NEWS
some title
NEWS
another title
PYTHON
another arbitrary title
NEWS
yet another title



I'd like to sort it thusly instead:



NEWS
some title
another title
yet another title
PYTHON
another arbitrary title



Alas, my mind keeps turning into a bowl of spaghetti when I try to come up with a method, so without further ado; how should I go about this bit?
I reckon that there's something off with calling the category from the post's metadata only to try and categorize the posts via the retrieved data, but aside from that, I'm somewhat lost.



Here's the template snippet from user_profile.html:



{% if user.post_set.exists %}
<p>
{% for post in user.post_set.all|dictsortreversed:"date_posted" %}
<span style="margin-right: 5px; padding: 3px 6px; border-radius:12px; color:#FFF; background-color:#FFA826;">{{ post.category }}</span><br/>
<a style="margin-left:3px;" href="{% url 'blog:post-detail' post.slug %}">{{ post.title|truncatechars_html:30 }}</a><br/>
{% endfor %}
</p>
{% endif %}


The models:



class Category(models.Model):
class Meta:
verbose_name = 'category'
verbose_name_plural = 'categories'

name = models.CharField(max_length=30)

def __str__(self):
return self.name


class Post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=60)
category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.CASCADE)
content = RichTextUploadingField(
external_plugin_resources=[(
'youtube',
'/static/ckeditor/ckeditor/plugins/youtube/',
'plugin.js'
)],
blank=True,
null=True,
)
date_posted = models.DateTimeField(default=timezone.now)
updated = models.DateTimeField(auto_now=True)
slug = models.SlugField(max_length=70, blank=True, null=True, help_text='<font color="red">don't. touch. the. slug. field. unless. you. mean. it.</font> (it will auto-generate, don't worry.)')

def __str__(self):
return self.title

def get_absolute_url(self):
return reverse('blog:post-detail', kwargs={'slug': self.slug})


And finally the view which relate to the post_list.html:



class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = '-date_posted'
paginate_by = 6


Should I be doing it in a different manner altogether, I wonder? And if so, what would be considered 'best practice'?



Thank you :)







python django






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 17 '18 at 12:32









Puto MikéPuto Miké

328




328













  • Hi, is the given solution not working? maybe removing dictsortreversed:"date_posted" from template might help with the answer. Anyways, if it does not work then it would be great what kind behavior are you getting. because it is odd as you have accepted and then unaccepted the solution. Cheers!!

    – ruddra
    Nov 17 '18 at 16:05













  • Yeah, I jumped the gun on accepting the answer, as it seemed like exactly what I'd like to do before trying it out. Sorry about that. I'm currently trying out different variations with the template combined with your advice (ie. omitting the dictsortreversed and adding a for loop for the categories within the post for loop), but still struggling. Ironically I managed to do the exact opposite of what I intended, i.e NEWS NEWS NEWS some arbitrary title another title PYTHON PYTHON PYTHON yet another title, the titles repeating for as many times as there are available posts.

    – Puto Miké
    Nov 17 '18 at 17:32






  • 1





    I will reaccept once I sort it out; was too embarrased to ask again. Just gimme a minute to sort it please.

    – Puto Miké
    Nov 17 '18 at 17:39











  • Sure, go ahead.

    – ruddra
    Nov 17 '18 at 17:42



















  • Hi, is the given solution not working? maybe removing dictsortreversed:"date_posted" from template might help with the answer. Anyways, if it does not work then it would be great what kind behavior are you getting. because it is odd as you have accepted and then unaccepted the solution. Cheers!!

    – ruddra
    Nov 17 '18 at 16:05













  • Yeah, I jumped the gun on accepting the answer, as it seemed like exactly what I'd like to do before trying it out. Sorry about that. I'm currently trying out different variations with the template combined with your advice (ie. omitting the dictsortreversed and adding a for loop for the categories within the post for loop), but still struggling. Ironically I managed to do the exact opposite of what I intended, i.e NEWS NEWS NEWS some arbitrary title another title PYTHON PYTHON PYTHON yet another title, the titles repeating for as many times as there are available posts.

    – Puto Miké
    Nov 17 '18 at 17:32






  • 1





    I will reaccept once I sort it out; was too embarrased to ask again. Just gimme a minute to sort it please.

    – Puto Miké
    Nov 17 '18 at 17:39











  • Sure, go ahead.

    – ruddra
    Nov 17 '18 at 17:42

















Hi, is the given solution not working? maybe removing dictsortreversed:"date_posted" from template might help with the answer. Anyways, if it does not work then it would be great what kind behavior are you getting. because it is odd as you have accepted and then unaccepted the solution. Cheers!!

– ruddra
Nov 17 '18 at 16:05







Hi, is the given solution not working? maybe removing dictsortreversed:"date_posted" from template might help with the answer. Anyways, if it does not work then it would be great what kind behavior are you getting. because it is odd as you have accepted and then unaccepted the solution. Cheers!!

– ruddra
Nov 17 '18 at 16:05















Yeah, I jumped the gun on accepting the answer, as it seemed like exactly what I'd like to do before trying it out. Sorry about that. I'm currently trying out different variations with the template combined with your advice (ie. omitting the dictsortreversed and adding a for loop for the categories within the post for loop), but still struggling. Ironically I managed to do the exact opposite of what I intended, i.e NEWS NEWS NEWS some arbitrary title another title PYTHON PYTHON PYTHON yet another title, the titles repeating for as many times as there are available posts.

– Puto Miké
Nov 17 '18 at 17:32





Yeah, I jumped the gun on accepting the answer, as it seemed like exactly what I'd like to do before trying it out. Sorry about that. I'm currently trying out different variations with the template combined with your advice (ie. omitting the dictsortreversed and adding a for loop for the categories within the post for loop), but still struggling. Ironically I managed to do the exact opposite of what I intended, i.e NEWS NEWS NEWS some arbitrary title another title PYTHON PYTHON PYTHON yet another title, the titles repeating for as many times as there are available posts.

– Puto Miké
Nov 17 '18 at 17:32




1




1





I will reaccept once I sort it out; was too embarrased to ask again. Just gimme a minute to sort it please.

– Puto Miké
Nov 17 '18 at 17:39





I will reaccept once I sort it out; was too embarrased to ask again. Just gimme a minute to sort it please.

– Puto Miké
Nov 17 '18 at 17:39













Sure, go ahead.

– ruddra
Nov 17 '18 at 17:42





Sure, go ahead.

– ruddra
Nov 17 '18 at 17:42












1 Answer
1






active

oldest

votes


















0














You can add the ordering in your model:



class Post(models.Model):
...
class Meta:
ordering = ['category', '-date_posted']


See the documentation for more details:



update



Maybe its better to use custom manager for this:



from django.db import models

class CustomManager(models.Manager):
# subclass model manager
def custom_category_dict(self, **kwargs):
# add a new method for building a dictionary
nDict = dict()
for i in self.get_queryset().filter(**kwargs): # filter queryset based on keyword argument passed to this method
current_list = nDict.get(i.category.name, )
current_list.append(i)
nDict.update({i.category.name: current_list})
return nDict

class Posts(models.Model):
# override posts model with manager
objects = CustomManager()


Usage:



# view

class PostListView(ListView):
...
def get_context_data(self, **kwargs):
context = super(PostListView, self).get_context_data(**kwargs)
context['category_wise_sorted_posts'] = Posts.objects.custom_category_dict() # you can pass filter logic as well, like Posts.objects.custom_category_dict(author_id=1)
return context


# template
{% for category, posts in category_wise_sorted_posts.items %}
<!-- Or {% for category, posts in user.posts_set.custom_category_dict.items %} -->
{{ category }}
{% for p in posts %}
{{ p.title }}

{% endfor %}
{% endfor %}





share|improve this answer


























  • Ok, I've been at it for a bit now, and while your advice clearly helped in terms of keeping the logic out of the html, also doing some of the sorting business automatically, I'm still struggling with the html end. I reckon I have to do something about the template, somehow calling the category foreign key before the post is called. A nested loop results in tons of repetition if not a None error.

    – Puto Miké
    Nov 18 '18 at 12:58











  • @PutoMiké can you please share what you have tried?

    – ruddra
    Nov 18 '18 at 16:03











  • FYI: I have tested with the ordering in Model and it seems to have reflected in every case, like: AAA - Nov. 8, 2018, 10:36 p.m. AAA - Nov. 8, 2018, 10:36 p.m. KKKK - Nov. 8, 2018, 10:38 p.m. BBBB - Nov. 7, 2018, 3:03 a.m. BBBB - Nov. 7, 2018, 3:03 a.m. CCC - Nov. 7, 2018, 3:03 a.m

    – ruddra
    Nov 18 '18 at 16:13











  • I might have been too vague in my description of the problem then. Using the format you suggest, I'm looking for something like: AAA - Nov. 8, 2018, 10:38 p.m. - Nov. 8, 2018, 10:36 p.m. - Nov. 7, 2018, 3:03 a.m. BBB - Nov. 7, 2018, 3:03 a.m. - Nov. 7, 2018, 3:00 a.m etc., the AAA and BBB representing the category and the date representing the post.

    – Puto Miké
    Nov 19 '18 at 11:03













  • @PutoMiké please see my update section. hope it helps.

    – ruddra
    Nov 19 '18 at 12:49











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53351299%2fretrieving-metadata-from-a-post-then-sorting-posts-by-said-metadata-in-django%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














You can add the ordering in your model:



class Post(models.Model):
...
class Meta:
ordering = ['category', '-date_posted']


See the documentation for more details:



update



Maybe its better to use custom manager for this:



from django.db import models

class CustomManager(models.Manager):
# subclass model manager
def custom_category_dict(self, **kwargs):
# add a new method for building a dictionary
nDict = dict()
for i in self.get_queryset().filter(**kwargs): # filter queryset based on keyword argument passed to this method
current_list = nDict.get(i.category.name, )
current_list.append(i)
nDict.update({i.category.name: current_list})
return nDict

class Posts(models.Model):
# override posts model with manager
objects = CustomManager()


Usage:



# view

class PostListView(ListView):
...
def get_context_data(self, **kwargs):
context = super(PostListView, self).get_context_data(**kwargs)
context['category_wise_sorted_posts'] = Posts.objects.custom_category_dict() # you can pass filter logic as well, like Posts.objects.custom_category_dict(author_id=1)
return context


# template
{% for category, posts in category_wise_sorted_posts.items %}
<!-- Or {% for category, posts in user.posts_set.custom_category_dict.items %} -->
{{ category }}
{% for p in posts %}
{{ p.title }}

{% endfor %}
{% endfor %}





share|improve this answer


























  • Ok, I've been at it for a bit now, and while your advice clearly helped in terms of keeping the logic out of the html, also doing some of the sorting business automatically, I'm still struggling with the html end. I reckon I have to do something about the template, somehow calling the category foreign key before the post is called. A nested loop results in tons of repetition if not a None error.

    – Puto Miké
    Nov 18 '18 at 12:58











  • @PutoMiké can you please share what you have tried?

    – ruddra
    Nov 18 '18 at 16:03











  • FYI: I have tested with the ordering in Model and it seems to have reflected in every case, like: AAA - Nov. 8, 2018, 10:36 p.m. AAA - Nov. 8, 2018, 10:36 p.m. KKKK - Nov. 8, 2018, 10:38 p.m. BBBB - Nov. 7, 2018, 3:03 a.m. BBBB - Nov. 7, 2018, 3:03 a.m. CCC - Nov. 7, 2018, 3:03 a.m

    – ruddra
    Nov 18 '18 at 16:13











  • I might have been too vague in my description of the problem then. Using the format you suggest, I'm looking for something like: AAA - Nov. 8, 2018, 10:38 p.m. - Nov. 8, 2018, 10:36 p.m. - Nov. 7, 2018, 3:03 a.m. BBB - Nov. 7, 2018, 3:03 a.m. - Nov. 7, 2018, 3:00 a.m etc., the AAA and BBB representing the category and the date representing the post.

    – Puto Miké
    Nov 19 '18 at 11:03













  • @PutoMiké please see my update section. hope it helps.

    – ruddra
    Nov 19 '18 at 12:49
















0














You can add the ordering in your model:



class Post(models.Model):
...
class Meta:
ordering = ['category', '-date_posted']


See the documentation for more details:



update



Maybe its better to use custom manager for this:



from django.db import models

class CustomManager(models.Manager):
# subclass model manager
def custom_category_dict(self, **kwargs):
# add a new method for building a dictionary
nDict = dict()
for i in self.get_queryset().filter(**kwargs): # filter queryset based on keyword argument passed to this method
current_list = nDict.get(i.category.name, )
current_list.append(i)
nDict.update({i.category.name: current_list})
return nDict

class Posts(models.Model):
# override posts model with manager
objects = CustomManager()


Usage:



# view

class PostListView(ListView):
...
def get_context_data(self, **kwargs):
context = super(PostListView, self).get_context_data(**kwargs)
context['category_wise_sorted_posts'] = Posts.objects.custom_category_dict() # you can pass filter logic as well, like Posts.objects.custom_category_dict(author_id=1)
return context


# template
{% for category, posts in category_wise_sorted_posts.items %}
<!-- Or {% for category, posts in user.posts_set.custom_category_dict.items %} -->
{{ category }}
{% for p in posts %}
{{ p.title }}

{% endfor %}
{% endfor %}





share|improve this answer


























  • Ok, I've been at it for a bit now, and while your advice clearly helped in terms of keeping the logic out of the html, also doing some of the sorting business automatically, I'm still struggling with the html end. I reckon I have to do something about the template, somehow calling the category foreign key before the post is called. A nested loop results in tons of repetition if not a None error.

    – Puto Miké
    Nov 18 '18 at 12:58











  • @PutoMiké can you please share what you have tried?

    – ruddra
    Nov 18 '18 at 16:03











  • FYI: I have tested with the ordering in Model and it seems to have reflected in every case, like: AAA - Nov. 8, 2018, 10:36 p.m. AAA - Nov. 8, 2018, 10:36 p.m. KKKK - Nov. 8, 2018, 10:38 p.m. BBBB - Nov. 7, 2018, 3:03 a.m. BBBB - Nov. 7, 2018, 3:03 a.m. CCC - Nov. 7, 2018, 3:03 a.m

    – ruddra
    Nov 18 '18 at 16:13











  • I might have been too vague in my description of the problem then. Using the format you suggest, I'm looking for something like: AAA - Nov. 8, 2018, 10:38 p.m. - Nov. 8, 2018, 10:36 p.m. - Nov. 7, 2018, 3:03 a.m. BBB - Nov. 7, 2018, 3:03 a.m. - Nov. 7, 2018, 3:00 a.m etc., the AAA and BBB representing the category and the date representing the post.

    – Puto Miké
    Nov 19 '18 at 11:03













  • @PutoMiké please see my update section. hope it helps.

    – ruddra
    Nov 19 '18 at 12:49














0












0








0







You can add the ordering in your model:



class Post(models.Model):
...
class Meta:
ordering = ['category', '-date_posted']


See the documentation for more details:



update



Maybe its better to use custom manager for this:



from django.db import models

class CustomManager(models.Manager):
# subclass model manager
def custom_category_dict(self, **kwargs):
# add a new method for building a dictionary
nDict = dict()
for i in self.get_queryset().filter(**kwargs): # filter queryset based on keyword argument passed to this method
current_list = nDict.get(i.category.name, )
current_list.append(i)
nDict.update({i.category.name: current_list})
return nDict

class Posts(models.Model):
# override posts model with manager
objects = CustomManager()


Usage:



# view

class PostListView(ListView):
...
def get_context_data(self, **kwargs):
context = super(PostListView, self).get_context_data(**kwargs)
context['category_wise_sorted_posts'] = Posts.objects.custom_category_dict() # you can pass filter logic as well, like Posts.objects.custom_category_dict(author_id=1)
return context


# template
{% for category, posts in category_wise_sorted_posts.items %}
<!-- Or {% for category, posts in user.posts_set.custom_category_dict.items %} -->
{{ category }}
{% for p in posts %}
{{ p.title }}

{% endfor %}
{% endfor %}





share|improve this answer















You can add the ordering in your model:



class Post(models.Model):
...
class Meta:
ordering = ['category', '-date_posted']


See the documentation for more details:



update



Maybe its better to use custom manager for this:



from django.db import models

class CustomManager(models.Manager):
# subclass model manager
def custom_category_dict(self, **kwargs):
# add a new method for building a dictionary
nDict = dict()
for i in self.get_queryset().filter(**kwargs): # filter queryset based on keyword argument passed to this method
current_list = nDict.get(i.category.name, )
current_list.append(i)
nDict.update({i.category.name: current_list})
return nDict

class Posts(models.Model):
# override posts model with manager
objects = CustomManager()


Usage:



# view

class PostListView(ListView):
...
def get_context_data(self, **kwargs):
context = super(PostListView, self).get_context_data(**kwargs)
context['category_wise_sorted_posts'] = Posts.objects.custom_category_dict() # you can pass filter logic as well, like Posts.objects.custom_category_dict(author_id=1)
return context


# template
{% for category, posts in category_wise_sorted_posts.items %}
<!-- Or {% for category, posts in user.posts_set.custom_category_dict.items %} -->
{{ category }}
{% for p in posts %}
{{ p.title }}

{% endfor %}
{% endfor %}






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 19 '18 at 12:54

























answered Nov 17 '18 at 12:57









ruddraruddra

13.8k32748




13.8k32748













  • Ok, I've been at it for a bit now, and while your advice clearly helped in terms of keeping the logic out of the html, also doing some of the sorting business automatically, I'm still struggling with the html end. I reckon I have to do something about the template, somehow calling the category foreign key before the post is called. A nested loop results in tons of repetition if not a None error.

    – Puto Miké
    Nov 18 '18 at 12:58











  • @PutoMiké can you please share what you have tried?

    – ruddra
    Nov 18 '18 at 16:03











  • FYI: I have tested with the ordering in Model and it seems to have reflected in every case, like: AAA - Nov. 8, 2018, 10:36 p.m. AAA - Nov. 8, 2018, 10:36 p.m. KKKK - Nov. 8, 2018, 10:38 p.m. BBBB - Nov. 7, 2018, 3:03 a.m. BBBB - Nov. 7, 2018, 3:03 a.m. CCC - Nov. 7, 2018, 3:03 a.m

    – ruddra
    Nov 18 '18 at 16:13











  • I might have been too vague in my description of the problem then. Using the format you suggest, I'm looking for something like: AAA - Nov. 8, 2018, 10:38 p.m. - Nov. 8, 2018, 10:36 p.m. - Nov. 7, 2018, 3:03 a.m. BBB - Nov. 7, 2018, 3:03 a.m. - Nov. 7, 2018, 3:00 a.m etc., the AAA and BBB representing the category and the date representing the post.

    – Puto Miké
    Nov 19 '18 at 11:03













  • @PutoMiké please see my update section. hope it helps.

    – ruddra
    Nov 19 '18 at 12:49



















  • Ok, I've been at it for a bit now, and while your advice clearly helped in terms of keeping the logic out of the html, also doing some of the sorting business automatically, I'm still struggling with the html end. I reckon I have to do something about the template, somehow calling the category foreign key before the post is called. A nested loop results in tons of repetition if not a None error.

    – Puto Miké
    Nov 18 '18 at 12:58











  • @PutoMiké can you please share what you have tried?

    – ruddra
    Nov 18 '18 at 16:03











  • FYI: I have tested with the ordering in Model and it seems to have reflected in every case, like: AAA - Nov. 8, 2018, 10:36 p.m. AAA - Nov. 8, 2018, 10:36 p.m. KKKK - Nov. 8, 2018, 10:38 p.m. BBBB - Nov. 7, 2018, 3:03 a.m. BBBB - Nov. 7, 2018, 3:03 a.m. CCC - Nov. 7, 2018, 3:03 a.m

    – ruddra
    Nov 18 '18 at 16:13











  • I might have been too vague in my description of the problem then. Using the format you suggest, I'm looking for something like: AAA - Nov. 8, 2018, 10:38 p.m. - Nov. 8, 2018, 10:36 p.m. - Nov. 7, 2018, 3:03 a.m. BBB - Nov. 7, 2018, 3:03 a.m. - Nov. 7, 2018, 3:00 a.m etc., the AAA and BBB representing the category and the date representing the post.

    – Puto Miké
    Nov 19 '18 at 11:03













  • @PutoMiké please see my update section. hope it helps.

    – ruddra
    Nov 19 '18 at 12:49

















Ok, I've been at it for a bit now, and while your advice clearly helped in terms of keeping the logic out of the html, also doing some of the sorting business automatically, I'm still struggling with the html end. I reckon I have to do something about the template, somehow calling the category foreign key before the post is called. A nested loop results in tons of repetition if not a None error.

– Puto Miké
Nov 18 '18 at 12:58





Ok, I've been at it for a bit now, and while your advice clearly helped in terms of keeping the logic out of the html, also doing some of the sorting business automatically, I'm still struggling with the html end. I reckon I have to do something about the template, somehow calling the category foreign key before the post is called. A nested loop results in tons of repetition if not a None error.

– Puto Miké
Nov 18 '18 at 12:58













@PutoMiké can you please share what you have tried?

– ruddra
Nov 18 '18 at 16:03





@PutoMiké can you please share what you have tried?

– ruddra
Nov 18 '18 at 16:03













FYI: I have tested with the ordering in Model and it seems to have reflected in every case, like: AAA - Nov. 8, 2018, 10:36 p.m. AAA - Nov. 8, 2018, 10:36 p.m. KKKK - Nov. 8, 2018, 10:38 p.m. BBBB - Nov. 7, 2018, 3:03 a.m. BBBB - Nov. 7, 2018, 3:03 a.m. CCC - Nov. 7, 2018, 3:03 a.m

– ruddra
Nov 18 '18 at 16:13





FYI: I have tested with the ordering in Model and it seems to have reflected in every case, like: AAA - Nov. 8, 2018, 10:36 p.m. AAA - Nov. 8, 2018, 10:36 p.m. KKKK - Nov. 8, 2018, 10:38 p.m. BBBB - Nov. 7, 2018, 3:03 a.m. BBBB - Nov. 7, 2018, 3:03 a.m. CCC - Nov. 7, 2018, 3:03 a.m

– ruddra
Nov 18 '18 at 16:13













I might have been too vague in my description of the problem then. Using the format you suggest, I'm looking for something like: AAA - Nov. 8, 2018, 10:38 p.m. - Nov. 8, 2018, 10:36 p.m. - Nov. 7, 2018, 3:03 a.m. BBB - Nov. 7, 2018, 3:03 a.m. - Nov. 7, 2018, 3:00 a.m etc., the AAA and BBB representing the category and the date representing the post.

– Puto Miké
Nov 19 '18 at 11:03







I might have been too vague in my description of the problem then. Using the format you suggest, I'm looking for something like: AAA - Nov. 8, 2018, 10:38 p.m. - Nov. 8, 2018, 10:36 p.m. - Nov. 7, 2018, 3:03 a.m. BBB - Nov. 7, 2018, 3:03 a.m. - Nov. 7, 2018, 3:00 a.m etc., the AAA and BBB representing the category and the date representing the post.

– Puto Miké
Nov 19 '18 at 11:03















@PutoMiké please see my update section. hope it helps.

– ruddra
Nov 19 '18 at 12:49





@PutoMiké please see my update section. hope it helps.

– ruddra
Nov 19 '18 at 12:49


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53351299%2fretrieving-metadata-from-a-post-then-sorting-posts-by-said-metadata-in-django%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

Tangent Lines Diagram Along Smooth Curve

Yusuf al-Mu'taman ibn Hud

Zucchini