djangopython-3.xdjango-modelsdjango-mysql

How do I update a table column with Django?


I'm trying to create an app with a form that when submitted, updates a table in my database based on the info submitted, but I'm not sure how to go about it. Currently, I have a simple mode:

class Client(models.Model):
    company_name = models.CharField(max_length=200)
    launchpad_id = models.PositiveIntegerField()
    client_email = models.EmailField()
    content_id = models.CharField(max_length=200)

    def __str__(self):
        return self.company_name + ' | ' + self.content_id

and my databases configured like so:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django_project',
        'USER': 'xxx',
        'PASSWORD': 'xxx',
        'HOST': 'xxxx',
        'PORT': 'xxx',
    },
    'info': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'reporting_database',
        'USER': 'xxx',
        'PASSWORD': 'xxx',
        'HOST': 'xxx',
        'PORT': 'xxx',
    }
}

What I want to happen is when I submit my fields through the Client model either in admin or a template, it updates my client_info table in the reporting_database. I cant seem to figure out how to make that connection work though. I would appreciate any direction you can give me. Thanks.


Solution

  • I was able to achieve my desired results by adding the following code to my model:

    def update_mysql(self):
        cursor = db.cursor()
        sql = "UPDATE tb_reporting_info SET client_email = '%s' WHERE content_id = '%s' AND launchpad_id = '%s';"
        cursor.execute( sql % (self.client_email, self.content_id, self.launchpad_id))
        db.commit()
    

    I set my form action to action="{% url 'contact:addClient' %}" and my view to:

    def addClient(request):
        if request.method == 'POST':
            # Set POST data to variables
            company_name = request.POST['company_name']
            launchpad_id = request.POST['launchpad_id']
            content_id = request.POST['content_id']
            client_email = request.POST['client_email']
            client_added = True  # Tells the template to render a success message
    
            # Pass POST data to Client object
            c = Client(company_name = company_name,
                    launchpad_id = launchpad_id,
                    content_id = content_id,
                    client_email = client_email
                    )
            c.update_mysql()
    

    It's bare bones but it works perfectly for what I need.