0

For a pet project, I am trying to display the posts and pictures sorted on the date created. Right now I can display them in sorted order but separately (like first posts in sorted order and then pictures in sorted order).

I would like to show them on the wall based on create date (regardless of whether it is a post or picture).

Models.py

class AddStatus(models.Model):
  user = models.ForeignKey(User, on_delete=models.CASCADE )
  status = models.TextField()
  date = models.DateTimeField(default=datetime.now)

class ImageLib(models.Model):
  user = models.ForeignKey(User, on_delete=models.CASCADE )
  picture = models.ImageField()
  date = models.DateTimeField(default=datetime.now)

Views.py

class ProfilePage(ListView):
  model = models.UserCreation
  context_object_name = 'profile'
    def get_context_data(self, *args, **kwargs):
      context = super(ProfilePage, self).get_context_data(*args, 
         **kwargs)
      user =self.request.user
      try:
        context['data'] = ProfileData.objects.get( user=user)
        context['add'] = AddStatus.objects.filter(user=user).order_by('-date')
        context['uploadpic'] = ImageLib.objects.filter(user=user).order_by('-date')
      except ProfileData.DoesNotExist:
        context['data']= None
        context['add']=None
        context['uploadpic'] = None
      return context

Template

{% for items in add %}
<h6 class="display-5" style="font-weight:1px"><i class="fas fa-plus-square"></i>&emsp;<strong class="capitalize">{{items.user.usercreation.fname}} {{items.user.usercreation.lname}}</strong><span style="font-size:16px; font-weight:1px"> wrote "{{items.status}}"</span>
<small style="font-size:0.7rem">&emsp;{{items.date.date}} at {{items.date.time}}</small><a style="float:right"  href="{% url 'usercreation:deletestatus' items.pk %}"><i class="fas fa-trash"></i></a></h6>
<hr>
{% endfor %}
{% for pics in uploadpic %}
<h6 class="display-5" style="font-weight:1px"><i class="fas fa-plus-square"></i>&emsp;<strong class="capitalize">{{pics.user.usercreation.fname}} {{pics.user.usercreation.lname}}</strong><span style="font-size:16px; font-weight:1px"> uploaded a picture</span>
<small style="font-size:0.7rem">&emsp;{{pics.date.date}} at {{pics.date.time}}</small><a style="float:right"  href="{% url 'usercreation:deletepic' pics.pk %}"><i class="fas fa-trash"></i></a></h6>
<img style="width:300px" src="{{pics.picture.url}}" alt="">
<hr>
{% endfor %}
Endre Both
  • 5,540
  • 1
  • 26
  • 31
  • 2
    Possible duplicate of [How to combine 2 or more querysets in a Django view?](https://stackoverflow.com/questions/431628/how-to-combine-2-or-more-querysets-in-a-django-view) – niekas Apr 20 '19 at 07:21

1 Answers1

0

You could use itertools.chain:

context['ordered_instances'] = sorted(
    chain(Post.objects.all(), Picture.objects.all()),
    key=lambda instance: instance.date)
niekas
  • 8,187
  • 7
  • 40
  • 58