1

我有这个非常简单的观点:

from models import Item, Tag, Category, User
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse

def save_item(request):
    try:
            print request.GET
        i = Item()
        i.user = User.objects.get_or_create(email=request.GET['user_email'][0])
        i.save()

        print i
    except Exception as e:
        print e.message()

    return HttpResponse()

使用这些非常简单的模型:

class User(models.Model):
    email = models.EmailField()

class Item(models.Model):
    category = models.ForeignKey(Category, null=True, blank=True)
    tags = models.ManyToManyField(Tag, null=True, blank=True)
    address = models.CharField(max_length = 512, null=True, blank=True)
    user = models.ForeignKey(User)
    data = models.CharField(max_length = 1024, null=True, blank=True)

打印是我的 error.log 中唯一显示的内容:

[Wed May 16 01:23:40 2012] [error] <QueryDict: {u'website': [u''], u'comment': [u''], u'rating': [u''], u'phone number': [u''], u'address': [u''], u'user_email': [u'cc.emeraldeyes@gmail.com']}>

但未创建 Item 模型实例!

我可以在管理员或 shell 中手动创建一个:

ubuntu@ip-10-196-47-228:~/WeShouldServer$ ./manage.py shell
Python 2.7.3 (default, Apr 20 2012, 22:39:59) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from RemoteStorage.models import Item
>>> i = Item()
>>> from RemoteStorage.models import User
>>> i.user = User.objects.get(pk=1)
>>> i.save()
# THIS WORKS

但试图在视图中保存一个...失败了。默默。为什么??!!!

4

1 回答 1

7

get_or_create返回元组

 user, created = User.objects.get_or_create(email=request.GET['user_email'][0])
于 2012-05-16T06:38:14.163 回答