I am trying to write a mySql trigger for a website database. The backend uses django framework.
def add_trigger():
trigger = "CREATE TRIGGER update_ppl_rating \
BEFORE INSERT ON demosite_peoplerating \
FOR EACH ROW \
BEGIN \
DECLARE total integer; \
DECLARE sum integer; \
DECLARE avg float; \
SELECT COUNT(*) INTO total FROM demosite_peoplerating GROUP BY apart_key HAVING apart_key = NEW.apart_key; \
SELECT SUM(rating) INTO total FROM demosite_peoplerating GROUP BY apart_key HAVING apart_key = NEW.apart_key; \
SET avg = sum/total; \
UPDATE demosite_ratingtable \
SET ppl_rating = avg \
FROM demosite_ratingtable \
WHERE apart_key = NEW.apart_key \
END;"
cursor = connection.cursor()
cursor.execute(trigger)
cursor.close()
Here is the database model related:
class RatingTable(models.Model):
apart_key = models.ForeignKey(
'ApartmentFeature',
on_delete=models.CASCADE,
unique=True,
primary_key=True
)
env_rating = models.FloatField()
ppl_rating = models.FloatField()
rest_05_count = models.IntegerField()
rest_1_count = models.IntegerField()
rest_2_count = models.IntegerField()
shop_05_count = models.IntegerField()
shop_1_count = models.IntegerField()
shop_2_count = models.IntegerField()
class PeopleRating(models.Model):
comment_id = models.AutoField(primary_key=True)
apart_key = models.ForeignKey(
'ApartmentFeature',
on_delete=models.CASCADE,
)
rating = models.IntegerField()
comment = models.CharField(max_length=200)
nick_name = models.CharField(max_length=200)
After running add_trigger(), mysql server replies:
django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM demosite_ratingtable WHERE apart_key = NEW.apart_key END' at line 1")
Could you please any one give me tha idea to solve this?
Related
What I want to accomplish is to get a unique list of the names of customers with their lastest consultation date.
I have defined these models in my models.py file, using mySQL as my database:
class Customer(models.Model):
class ContactChoice(models.IntegerChoices):
DO_NOT_CONTACT = 0
EMAIL = 1
TXT_SMS_VIBER = 2
mobile_num = models.CharField('Mobile Number', max_length=10, unique=True,)
email_add = models.EmailField('Email', max_length=150, unique=True,)
last_name = models.CharField('Last Name', max_length=30,)
first_name = models.CharField('First Name', max_length=30,)
contact_for = models.CharField('Contact For', max_length=60,)
contact_on = models.IntegerField('Contact Using', choices=ContactChoice.choices, default=0,)
customer_consent = models.BooleanField('With Consent?', default=False,)
def __str__(self):
return self.last_name + ', ' + self.first_name
class Consultation(models.Model):
consultation_date = models.DateTimeField('Date of Consultation', default=now)
customer = models.ForeignKey(Customer, on_delete=models.SET_DEFAULT, default=1)
concern = models.ForeignKey(SkinConcern, on_delete=models.SET_DEFAULT, default=1)
consultation_concern = models.CharField('Other Concerns', max_length=120, null=True,)
product = models.ForeignKey(Product, on_delete=models.SET_DEFAULT, default=1)
user = models.ForeignKey(User, on_delete=models.SET_DEFAULT, default=1)
store = models.ForeignKey(Store, on_delete=models.SET_DEFAULT, default=1)
consultation_is_active = models.BooleanField('Is Active', default=True)
def __str__(self):
return self.customer.last_name + ", " + self.customer.first_name
In my views.py, I have this for the Consultations page:
distinct = Consultation.objects.values('customer').annotate(consultation_count=Count('customer')).filter(consultation_count=1)
consults = Consultation.objects.filter(customer__in=[item['customer'] for item in distinct])
As mentioned, I was expecting to get a unique list of customer names with their latest consultation dates. This code results in only 1 record being shown.
Can you point me in the right direction for this? Thank you in advance! :)
As I see it, what you're doing right now is gathering all the customers that only had one consultation. This won't return what you want.
I believe you can use the latest() method for this: https://docs.djangoproject.com/en/4.1/ref/models/querysets/#latest
This is untested code, but you could do something like this:
# gather all the customers
customers = Customer.objects.all()
# for every customer, get their latest consultation date, using the .latest() function
for customer in customers:
try:
latest_consultation = Consultation.objects.filter(customer=customer).latest('consultation_date')
latest_consultation_date = latest_consultation.consultation_date
except Consultation.DoesNotExist:
latest_consultation_date = None
customer.latest_consultation_date = latest_consultation_date
you can then loop over it as so:
for customer in customers:
if customer.latest_consultation_date:
print(customer.latest_consultation_date)
I have a simple Table like this
class Employeecode(Base):
__tablename__ = 'employeecode'
id = Column(Integer, primary_key=True)
unique_code = Column(String(5), unique=True)
employe_name = Column(String(50))
designation = Column(String(50))
How i can create a function which will insert value into 'employeecode' table if 'unique_code' column doesn't have that value.
insert_unique(unique_code,employe_name,designation)
First you can store all previous unicode_value in a list and then you can check and run your query..
def function(**kwargs):
session = Session()
unique_list =[]
employeecodes = db.session.query(Employeecode).all()
for employee in employeecodes:
unique_list.append(employee.unique_code)
if kwargs['unique_code'] not in unique_list:
employee = Employeecode()
employee.unique_code = kwargs['unique_code']
employee.employe_name = kwargs['employe_name']
employee.designation = kwargs['designation']
session.commit()
retval = row2dict(employee)
session.close()
return retval
else:
pass
I am trying to get only approved responses (staged>1) but for some reason the Reply.staged>1 in the primaryjoin is not working
I am very new to sqlAlchemy so I am not really sure what the relationship for parent is doing with the remote_side
class Story(Base):
__tablename__ = ’Story'
id = Column(‘ID', Integer, primary_key=True)
anonymous = Column(TINYINT)
detail = Column('detail',String, js_name='detail')
summary = Column('summary',String, js_name='questionSummary')
user_id = Column('uid', Integer, ForeignKey('rlUser.uid'), js_name='userId')
user = relationship("User")
inspire_id = Column('inspireID', Integer, js_name='inspireId')
staged = Column(TINYINT)
class Reply(Base):
__tablename__ = 'Reply'
id = Column('replyID', Integer, primary_key=True)
parent_id = Column('parentID', Integer, ForeignKey('rlReply.replyID'),js_name='parentId')
user_id = Column('userID', Integer, js_name='userId')
detail = Column(String, js_name='detail')
reply_date = Column('replyDate', TIMESTAMP, js_name='replyDate')
expertise_type = Column('expertiseType', Integer, js_name='expertiseType')
status = Column(Integer)
staged = Column(Integer)
story = relationship(“Story",primaryjoin='and_(Reply.story_id == Story.id, Reply.parent_id==0, Reply.staged>1)', backref=backref("replies", uselist=True ))
parent = relationship('Reply',primaryjoin='and_(Reply.parent_id==Reply.id, Reply.staged>1)', backref='responses', remote_side='Reply.id', viewonly=True, uselist=True)
def __init__(self):
self.staged = constants.POST_QUEUE_STATUS['STAGED']
#property
def reply_count(self):
return len(self.responses)
The where clause for story.replies:
WHERE Reply.rushlineID = %s AND Reply.parentID = %s AND Reply.staged > %s
parms sqlalchemy.engine.base.Engine (110L, 0, 1)
Which is perfect, however:
the where clause for story.replies[0].responses:
WHERE Reply.parentID = %s AND %s > %s
params are sqlalchemy.engine.base.Engine (68L, 2, 1)
what I need is WHERE Reply.parentID = %s AND AND Reply.staged > %s AND %s > %s
sqlalchemy.engine.base.Engine (68L, 1, 2, 1)
The magic incantation for this, I have to admit, I got to through trial and a lot of error. Here are the relevant bits:
parent_id = RlColumn('parentID', Integer,
ForeignKey('rlReply.replyID'),
js_name='parentId')
parent = RlRelationship('Reply',
primaryjoin='and_(Reply.parent_id==remote(Reply.id),Reply.flagged_status <2)',
remote_side=id, uselist=True,
foreign_keys=parent_id, backref='replies')
models.py is
class Book(models.Model):
book_name=models.CharField(max_length=30)
author_name=models.CharField(max_length=30)
publisher_name=models.CharField(max_length=40)
author=models.ForeignKey(Author)
def __unicode__(self):
..........
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
age=models.IntegerField()
def __unicode__(self):
........
def books(self):
return Book.objects.filter(author=self)
I need to perform edit and save the already existing data in a table from database.I am using 2 models.since i did for doing the same by single table,have some confusion to perform with two table.I am a learner of django.plz help me with this
plz check my views.py for edit option.
def editbook(request,book_id):
if request.POST:
book_name =request.POST['book_name']
publisher_name =request.POST['publisher_name']
books=Book.objects.filter(book_id=book_id).update(book_name=book_name, publisher_name=publisher_name)
first_name = request.POST.get('first_name')
last_name = request.POST.get('last_name')
email = request.POST.get('email')
age = request.POST.get('age')
author = Author.objects.update(first_name = first_name,last_name = last_name,email=email,age=age)
return redirect('/index/')
else:
books = Book.objects.get(pk=book_id)
return render_to_response('editbook.html',{'books':books},context_instance=RequestContext(request))
ya.this is not working properlly.plz guide me how to perform that.
def editbook(request,book_id):
books = Book.objects.get(pk=book_id)
if request.POST:
book_name = request.POST.get('book_name')
publisher_name = request.POST.get('publisher_name')
books.book_name = book_name
books.publisher = publisher_name
get_author = books.save()
first_name = request.POST.get('first_name')
last_name = request.POST.get('last_name')
email = request.POST.get('email')
age = int(request.POST.get('age'))
author = Author.objects.get(pk=get_author.author_id)
author.first_name = first_name
author.last_name = last_name
author.email = email
author.age = age
author.save()
return redirect('/index/')
return render_to_response('editbook.html',{
'books':books
},context_instance=RequestContext(request))
Hi I have a project in PHP and I want develop the same with Django, for many reasons I decided to create a new database, so now I have to export all the data from the old one to the new one,for doing that I use the models I developed for Django, it worked until I stuck with this error:
_mysql_exceptions.Warning: Data truncated for column 'bloomberg' at row 1
this is the model of the table where I am experimenting this issue:
class Contact(models.Model):
company_id = models.ForeignKey(Company)
address = models.CharField(max_length=150)
first_name= models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
role = models.CharField(max_length=20)
sector = models.CharField(max_length=45)
work_phone = models.CharField(max_length=30)
contact_source = models.CharField(max_length=30)
alt_work_phone = models.CharField(max_length=30)
mobile_phone = models.CharField(max_length=30)
work_fax = models.CharField(max_length=30)
bloomberg = models.CharField(max_length=60)
work_email = models.CharField(max_length=60)
research_email = models.CharField(max_length=60)
product_focus = models.CharField(max_length=2)
preferred_email = models.CharField(max_length=60)
job_title = models.CharField(max_length=80)
created_by = models.CharField(max_length=25)
legal_entity_name = models.CharField(max_length=100)
status= models.ForeignKey(Status)
title = models.CharField(max_length=5)
zipcode = models.CharField(max_length=10)
country = models.CharField(max_length=15)
city= models.CharField(max_length=20)
created_date=models.DateTimeField('creation date ')
updated_date=models.DateTimeField('update date ')
updated_by = models.CharField(max_length=20)
parent = models.CharField(max_length=45)
address_line_2 = models.CharField(max_length=100)
new = models.BooleanField()
hided = models.BooleanField()
employee = models.BooleanField()
def __unicode__(self):
s = u" Contact "
return s + self.first_name + " " + self.last_name
the fields in both databases have the same length,so I do not understand the error, after googling I noticed that usually this problem is solved fixing the dimensions of the column, but this is not my case. can somebody tell me how to fix it?
it looks like 60 Chars are not enough for your "bloombergs". Try to set this higher like:
bloomberg = models.CharField(max_length=255)
Notice, that you will also have to do this on database level if you already synced your models. Hope this helps.