Reputation: 125
Let's think I build Instagram platform.
**I need to lookup fast
I have 2 models:
class Follower():
hastags = ???
class Hashtag():
name = char...
ABILITY:
To be able to fetch -all specific follower- hashtags.
And reverse: fetch -all Followers- of a specific hastags.
NOTES:
A Follower don't have to have an hashtag.
An Hashtag exist only once a follower is adding it.
I think I can put a foreginKey on Hashtag instead of Follower but this seems to be messy since I mostly deal with the followers not the hashtags. I know I can add a funtion to add hashtag to follower in the follower model.
So best option is to use ManyToMany from Followers to Hashtags ? correct me if I am wrong ?
EXAMPLE:
Follower1 uses Hashtags: Tag1, Tag2
Follower2 uses Hashtags: Tag2, Tag3
Upvotes: 1
Views: 77
Reputation: 169085
Yes, you'd use a many-to-many field.
class Follower(models.Model):
followed_hashtags = models.ManyToManyField('Hashtag', related_name='followers')
To get all of the hashtags followed by someone, you can use the forward descriptor
hashtags = follower.followed_hashtags.all()
To get all of the followers for a hashtag, you can use the reverse descriptor
cat_hashtag = Hashtag.objects.get(name='cat')
cat_followers = cat_hashtag.followers.all()
You can also use the implicitly generated through
table/model for even more interesting lookups, such as summaries of follow counts:
HashtagFollows = Follower.followed_hashtags.through
counts = HashtagFollows.objects.all().values('hashtag__name').annotate(count=Count())
This implicit table can also be used for lookups if you only have e.g. a follower ID:
follower_8s_hashtag_names = HashtagFollows.objects.filter(follower_id=8).values_list('hashtag__name')
And, if you need to e.g. store when a given Follower started following a hashtag, see extra-fields-on-many-to-many-relationships (which then replaces the implicit through table).
Upvotes: 2