I have these models
and I have burnt all the night trying to figure how I could save to Likes
table but it won't just work.
class Users(models.Model):
email = models.EmailField()
name = models.CharField(max_length=60)
class Posts(models.Model):
user_id = models.ForeignKey('Users')
content = models.CharField(max_length=480)
class Likes(models.Model):
post_id = models.ForeignKey('Posts', related_name='likes_set')
user_id = models.ForeignKey('Users')
status = models.IntegerField()
Say user_id1 = 1
and truly exist in the table, post_id11 = 11
and also exist, and this user clicks on this post.
Now I want to save to Likes table and this is what I did;
user = Users.objects.get(id = user_id1)
post = user.posts_set.get(id = post_id11)
try:
liked = post.likes_set.get(user_id = user_id1)
except Likes.DoesNotExist:
liked = None
if liked:
liked.status = F('status') - 1
liked.save()
total_likes = liked.status
return HttpResponse(total_likes)
else:
post.likes_set.create(user_id = user_id1, post_id = post_id11, status = 1)
post.likes = F('likes') + 1
post.save()
total_likes = post.likes
return HttpResponse(total_likes)
And this the ERROR:
ValueError at /myapp/likeRecorder/
Cannot assign "1": "Likes.user_id" must be a "Users" instance.
I have googled all night trying to solve this. Help!