3

I have following models:

class Hashtag(models.Model):
    ...
    created = models.DateTimeField(auto_now_add=True)
    ...

class Tweet(models.Model):
    ...
    hashtags = models.ManyToManyField(
        to='Hashtag',
        through='TweetHashtag',
        through_fields=('tweet', 'hashtag'),
    )
    ...


class TweetHashtag(models.Model):
    comment = models.ForeignKey(
        to='Tweet',
        on_delete=models.CASCADE,
    )
    hashtag = models.ForeignKey(
        to='Hashtag',
        on_delete=models.CASCADE,
        related_name="tweets"
    )
    created = models.DateTimeField(auto_now_add=True)

My problem is when I get a Tweet, I want to get hashtags order by created.

tweet = Tweet.objects.get(id=1)
hashtags = list(tweet.hashtags.all())

When I check hashtags, I see the hashtags are in incorrect ordering. I want to get tweet.hashtags order by through_model.created (created of TweetHashtag model.)

Is there anyway? I have one idea but I don't know how to do that. The idea is to override relation manager of hashtags in Tweet model.

Is there any way?

msln
  • 1,318
  • 2
  • 19
  • 38

1 Answers1

1

You can order the HashTags with .order_by(…) [Django-doc]:

tweet = Tweet.objects.get(id=1)
hashtags = list(tweet.hashtags.order_by('tweethashtag__created'))
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • I need to set this `tweethashtag__created` as default ordering of the `tweet.hashtags.all()`. Is it possible? – msln Jan 17 '22 at 19:50
  • 2
    @msln: no, you can not specify a default ordering: the ordering of the through model is ignored when accessing the items of a `ManyToManyField`. – Willem Van Onsem Jan 17 '22 at 19:55