简体   繁体   中英

Raw SQL query in Django

Is there any nothing wrong with this raw query?

Worker.objects.raw('Delete from customer_worker Where customer_ptr_id= %s', [customer.id])

Customer id returns a string, but it seems like nothing happen, the object is still there after the execution.

The object Worker is a child object from Customer , I want to remain the customer, but delete the Worker object.

Here are the Customer and Worker models:

class Customer(User):                                                    
    slug=models.SlugField(unique=True)
    description=models.TextField(null=True)
    phone=models.IntegerField(null=True)
    isWorker=models.BooleanField()

    def save(self,*args,**kwargs):                                        
        self.slug=slugify(self.username)                                          
        super(Customer,self).save(*args, **kwargs)                             

    def __unicode__(self):
        return self.username


class Worker(Customer):
    comment=models.ForeignKey(Comment, null=True)
    keyword=models.ManyToManyField('job.JobGenre', null=True)

    def __unicode__(self):
        return self.username

You can delete your record(s) directly via connection.cursor() ( docs ):

from django.db import connection

cursor = connection.cursor()
cursor.execute('DELETE FROM costumer_worker WHERE costumer_ptr_id = %s', [costumer.id])
connection.commit()

But, the thing you're trying to do looks too simple to write SQL directly, use django ORM instead.

You may be missing comitting the transcation. Based on your settings, you may need to add : transaction.commit_unless_managed() in django 1.4 ( not needed in django 1.5, since default settings are different)

use this line:

from django.db import connection, transaction
cursor = connection.cursor()
with transaction.commit_on_success():
   cursor.execute('DELETE FROM costumer_worker WHERE costumer_ptr_id = %s', [costumer.id])
   connection.commit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM