Django获取刚刚创建的对象,但不返回任何内容

时间:2018-08-09 11:43:02

标签: django

我有一个观点:

if request.method == "POST":
    if request.user.is_authenticated:
        if request.is_ajax():
            try:
                post = Post.objects.all().last()
            except:
                return JsonResponse({'res': 0})
            print('got post: ' + str(post))
            try:
                post_chat_create = PostChat.objects.create(post=post, kind=POSTCHAT_TEXT, before=None, you_say=True, uuid=uuid.uuid4().hex)
                print('post chat has been created')
            except Exception as e:
                print('if it has exception: ' + str(e))
            print('just created post chat: ' + str(post_chat_create.pk))

            try:
                post_chat_last = PostChat.objects.all().last()
                print('any made post chat?: ' + str(post_chat_last))

            except PostChat.DoesNotExist:
                print('has error on getting post_chat_last')
            print('has no error on getting post_chat_last')

我认为这很奇怪,因为它打印出类似这样的内容:

在终端上打印:

获得帖子:帖子pk:2,用户:useruser1

帖子聊天已创建

刚刚创建的聊天室:32

是否有任何聊天帖子?:postchat:无

获取post_chat_last没有错误

问题: 为什么?当然,有一个PostChat对象的创建。由于存在此终端线路:just created post chat: 32

但是print('any made post chat?: ' + str(post_chat_last))这行返回: any made post chat?: postchat: None

这很奇怪。

刚刚被设置为PostChat,但无法获取。

为什么会这样?

这是models.py:

class Post(models.Model):

    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
    title = models.TextField(max_length=1000, null=True, blank=True, default=None)
    description = models.TextField(max_length=2000, null=True, blank=True, default=None)
    has_another_profile = models.BooleanField(default=False)
    is_open = models.BooleanField(default=True)
    uuid = models.CharField(max_length=34, unique=True, default=uuid.uuid4().hex)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

class PostChat(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, blank=True)
    you_say = models.BooleanField(default=True)
    before = models.ForeignKey("PostChat", on_delete=models.CASCADE, null=True, blank=True)
    kind = models.PositiveSmallIntegerField(choices=KINDS_CHOICES, default=0)
    uuid = models.CharField(max_length=34, unique=True, default=uuid.uuid4().hex)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

感谢阅读。

0 个答案:

没有答案