Skip to content

Commit

Permalink
89 - ManyToManyField and Reverse Relations
Browse files Browse the repository at this point in the history
  • Loading branch information
codingforentrepreneurs committed Jan 8, 2020
1 parent bca61a2 commit c52b4ca
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 2 deletions.
Binary file modified db.sqlite3
Binary file not shown.
20 changes: 20 additions & 0 deletions tweets/migrations/0006_auto_20200108_2040.py
@@ -0,0 +1,20 @@
# Generated by Django 2.2 on 2020-01-08 20:40

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
('tweets', '0005_tweet_parent'),
]

operations = [
migrations.AlterField(
model_name='tweet',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tweets', to=settings.AUTH_USER_MODEL),
),
]
2 changes: 1 addition & 1 deletion tweets/models.py
Expand Up @@ -13,7 +13,7 @@ class Tweet(models.Model):
# Maps to SQL data
# id = models.AutoField(primary_key=True)
parent = models.ForeignKey("self", null=True, on_delete=models.SET_NULL)
user = models.ForeignKey(User, on_delete=models.CASCADE) # many users can many tweets
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="tweets") # many users can many tweets
likes = models.ManyToManyField(User, related_name='tweet_user', blank=True, through=TweetLike)
content = models.TextField(blank=True, null=True)
image = models.FileField(upload_to='images/', blank=True, null=True)
Expand Down
11 changes: 10 additions & 1 deletion tweets/tests.py
Expand Up @@ -42,13 +42,22 @@ def test_tweet_list(self):
self.assertEqual(response.status_code, 200)
self.assertEqual(len(response.json()), 3)

def test_tweets_related_name(self):
user = self.user
self.assertEqual(user.tweets.count(), 2)

def test_action_like(self):
client = self.get_client()
response = client.post("/api/tweets/action/",
{"id": 1, "action": "like"})
self.assertEqual(response.status_code, 200)
like_count = response.json().get("likes")
user = self.user
my_like_instances_count = user.tweetlike_set.count()
my_related_likes = user.tweet_user.count()
self.assertEqual(response.status_code, 200)
self.assertEqual(like_count, 1)
self.assertEqual(my_like_instances_count, 1)
self.assertEqual(my_like_instances_count, my_related_likes)

def test_action_unlike(self):
client = self.get_client()
Expand Down

0 comments on commit c52b4ca

Please sign in to comment.