Django AutoField增量 [英] Django AutoField increment

查看:107
本文介绍了Django AutoField增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想自动递增一个不是主键的模型字段 conversation-id
目前,我使用以下代码行,这是非常低效的。

Well I want to auto-increment an model field conversation-id which is not a primary key. Currently, I'm using the following lines of codes, which is very inefficient.

web_query_data = WebQuery.objects.all()

        if not web_query_data:
            c_id = 0
        else:
            for data in web_query_data:
                c_id = data.conversation_id


        web_query = WebQuery.objects.create(user_id = request.user.id, sent_to = selected_users, 
                                            user_query = query,date_time = date_time, conversation_id = c_id + 1)

它基本上使用一个字段 conversation_id 循环并将其递增1。

It basically gets the last value of field conversation_id using a loop and increments it by 1 .

我尝试使用 models.Autofield ,这需要该字段为主。但是根据我的需要,我需要插入一些数据,这些数据有时与 conversation_id

I tried using models.Autofield which requires the field to be primary. But according to my needs , I need to insert a data which is sometimes duplicate to the conversation_id

推荐答案

您可以从这里获取最后一个对象并递增:

You can just get the last object and increment from here:

query = WebQuery.objects.all().order_by("-id")[0]
new_query = WebQuery.objects.create(user_id = request.user.id,
                                    sent_to = selected_users,
                                    user_query = query,
                                    date_time = date_time,
                                    conversation_id = query.conversation_id + 1)

(假设id是您的 WebQuery的主键模型)

(assuming that "id" is the primary key of your WebQuery model)

我不知道有没有办法在Django模式中自动执行。

I don't know if there is a way to do this automatically in a Django model though.

这篇关于Django AutoField增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆