Answer the question
In order to leave comments, you need to log in
How to make custom sqlite query in django rest?
there is a delete method in django-rest application
I make this query in DB Browser fro Sqlite and it works:
CREATE TABLE `new_category1` (
`id` integer NOT NULL PRIMARY KEY AUTOINCREMENT,
`question` text NOT NULL,
`answer` text NOT NULL
);
INSERT INTO new_category1(question, answer) SELECT question, answer FROM api_category1;
DROP TABLE api_category1;
ALTER TABLE new_category1 RENAME TO api_category1;
def delete(self, request, id):
category = self.get_object(self, id)
category.delete()
category.objects.raw('CREATE TABLE "new_category1" '
'("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, '
'"question" text NOT NULL, '
'"answer" text NOT NULL);')
return Response(status=status.HTTP_204_NO_CONTENT)
Answer the question
In order to leave comments, you need to log in
Thanks to @Dr.Bacon's tip, I made a pure sql query in this way:
oldTableName = "api_category1"
newTableName = "new_category1"
createTable = 'CREATE TABLE {newTableName} ' \
'(id integer NOT NULL PRIMARY KEY AUTOINCREMENT, ' \
'question text NOT NULL, ' \
'answer text NOT NULL);'
insertIntoTable = 'INSERT INTO {newTableName} (question, answer) SELECT question, answer FROM {oldTableName};'
dropTable = 'DROP TABLE {oldTableName};'
renameTable = 'ALTER TABLE {newTableName} RENAME TO {oldTableName};'
class Category1Details(APIView):
@staticmethod
def get_object(self, id):
try:
return Category1.objects.get(id=id)
except Category1.DoesNotExist:
return HttpResponse(status=status.HTTP_404_NOT_FOUND)
def get(self, request, id):
question = self.get_object(self, id)
serializer = Category1Serializer(question)
return Response(serializer.data)
def delete(self, request, id):
category = self.get_object(self, id)
oldTableName = "api_category1"
newTableName = "new_category1"
category.delete()
cursor = connection.cursor()
cursor.execute(createTable.format(newTableName=newTableName))
cursor.execute(insertIntoTable.format(newTableName=newTableName, oldTableName=oldTableName))
cursor.execute(dropTable.format(oldTableName=oldTableName))
cursor.execute(renameTable.format(newTableName=newTableName, oldTableName=oldTableName))
return Response(status=status.HTTP_204_NO_CONTENT)
If you have DDL queries there, then it is most likely a design error.
If this is DML, then Model.objects.raw is used if data mapping is needed in the Django model, and if not, then https://docs.djangoproject.com/en /3.0/topics/db/sq... Read about raw in the same place, otherwise you also use it incorrectly, you need to call it not on the object, but on the model class https://docs.djangoproject.com/en/3.0/topics/ db/sq...
So read docks, everything is there. Well, before using DRF, you need to understand how Django works
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question