有一个功能:
def Add_tag(request):
if request.user.is_authenticated():
if request.method == 'POST':
form = TagsForm(request.POST)
if form.is_valid():
# Get value
item_id = form.cleaned_data['item_id']
text = form.cleaned_data['text']
user = request.user
model_type = ContentType.objects.get(app_label='tags', model='Tag')
# Get or create user rating
try:
obj_t = Tag.objects.get(user_id=user.id, content_type_id=model_type.id, object_id=item_id)
except ObjectDoesNotExist:
obj_t = Tag.objects.create(user_id=user.id, content_type_id=model_type.id, object_id=item_id)
obj_t.text = text
obj_t.save()
return HttpResponse(status=200)
模型
class Tag(models.Model):
user = models.ForeignKey(User)
text = models.CharField(max_length=100, blank=True, verbose_name=_('name'))
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
def __unicode__(self):
return '%s %s' % self.user
该函数应该只创建一个对象。在第一次通话中,他创造了;第二个 - 更新...第三个(或 4/5/6/7 .. 88/99/100 .. random)(相同的值)再次创建。
为什么创建它?
MySQL,Django 1,5