Insert direct tuple with SQL in a Django view

Asked

Viewed 61 times

0

I’m using Django in two projects (let’s call Project1 and Project2) that relate and share the same database, but because they are different projects, they do not share the same apps.

Now I need to create, in Project1, information that will be used in Project2. But since I don’t have apps I can’t access the model and create as I would if it was all in the same project.

I already created the model in Project2 and was able to access the information in a Project1 view:

class ListCategoriesView(ListView):

 template_name = 'account_plan/list_categories.html'

def get_context_data(self,  **kwargs):
    context = super(ListCategoriesView, self).get_context_data(**kwargs)
    context.update({'categories': self.get_queryset()})
    return context

def get_queryset(self):
    with connection.cursor() as cursor:
        cursor.execute("""SELECT * FROM expenses_accountplan;""")
        categories = dictfetchall(cursor)

    return categories

In the template the information is displayed correctly, but I am not getting Createview with an Insert to create a new tuple. What I tried:

class CreateCategoryView(CreateView):
    template_name = 'account_plan/create_category.html'
    success_url = 'account_plan/list'

def insert(self):
    cursor = connection.cursor()
    query = '''INSERT INTO expenses_accountplan (category) VALUES ('categoria2');'''

    cursor.execute(query)
    transaction.commit()

def form_valid(self, form):
    return super(CreateCategoryView, self).form_valid(form)

def get_success_url(self):
    return self.success_url

This is returning the following error:

Improperlyconfigured at /Units/account_plan/create Createcategoryview is Missing a Queryset. Define Createcategoryview.model, Createcategoryview.queryset, or override Createcategoryview.get_queryset().

How can I do that? Or do you have a better way to access model data from the other project? I feel that using SQL commands in Django is not very suitable.

1 answer

0

I went through a similar situation which I solved using Django Rest Framework to perform the operations. Create the endpoints in project 2 and access through project 1, you can create views to search, insert, edit and delete information in project 2 and access everything through project 1 without having to use SQL manually inside the views. In the link below you will find a tutorial to create your api using DRF: https://scotch.io/tutorials/build-a-rest-api-with-django-a-test-driven-approach-part-1 In this tutorial you will see how to create the API with all operations and still with authentication.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.