Reputation: 17412
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)
It basically gets the last value of field conversation_id
using a loop and increments it by 1 .
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
Is there any better and efficient method for the same?
Upvotes: 0
Views: 1284
Reputation: 2189
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)
(assuming that "id" is the primary key of your WebQuery
model)
I don't know if there is a way to do this automatically in a Django model though.
Upvotes: 1