问题
I am not getting a clear picture regarding the Model (Like) object is not iterable.
Error
liked, created = Like.objects.create(question=create_id)
TypeError: 'Like' object is not iterable
model.py
class Question(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length= 200)
description = models.TextField()
location = models.CharField(max_length=150)
tags = TaggableManager()
time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.title
class Like(models.Model):
user = models.ManyToManyField(User, related_name='likes')
question = models.ForeignKey(Question)
date = models.DateTimeField(auto_now_add=True)
likecount = models.IntegerField(default=0)
urls.py
url(r'^like/$', 'apps.question.views.like', name='like'),
views.py
def like(request):
vars = {}
if request.method == 'POST':
user = request.user
tutorial_id = request.POST.get('tutorial_id', None)
create_id = get_object_or_404(Question, id=tutorial_id)
liked, created = Like.objects.create(question=create_id)
try:
user_liked = Like.objects.get(question=create_id, user=user)
except:
user_liked = None
if user_liked:
user_liked.likecount -= 1
liked.user.remove(request.user)
user_liked.save()
else:
liked.user.add(request.user)
liked.likecount += 1
liked.save()
return HttpResponse(simplejson.dumps(vars, user),
mimetype='application/javascript')
template
<button type="button" class="btn btn-request" name="{{question.id}}" id="like">Request</button>
<script>
$('#like').click(function(){
$.ajax({
type: "POST",
url: "{% url 'like' %}",
data: {'tutorial_id': $(this).attr('name'), 'csrfmiddlewaretoken': '{{csrf_token}}'},
dataType: "text",
success: function(response) {
alert('You liked this')
},
error: function(rs, e) {
alert(rs.responseText);
}
});
})
</script>
What I am missing here, can anyone explain me?
Thanks!
回答1:
Like.objects.create(question=create_id)
Returns a single object (a Like
).
So, doing like, created = Like.objects.create(question=create_id)
doesn't work because there's only one item on the right, so it can't be unpacked (like if you did like, created = 1
).
The method that returns the object and a created
boolean object is get_or_create:
like, created = Like.objects.get_or_create(question=create_id)
来源:https://stackoverflow.com/questions/22070607/django-typeerror-like-object-is-not-iterable-ajax-request