I am trying to add a COLUMN to certain table using psycopg2, from a Django function to a table in PostgreSQL. The name of the column is define in the views.py file of the Django project.
I have been trying with a some similar questions in stack over flow but none have worked for me.
View:
def parameter_creation(request):
if request.method == 'POST':
name = request.POST['name']
min_value = request.POST['min_value']
max_value = request.POST['max_valu']
if ParameterModel.objects.filter(name=unidecode(name.upper())).exists():
return JsonResponse('name', safe = False)
else:
form = New_Parameter_Form(request.POST)
if form.is_valid():
info = form.save(commit = False)
info.name = unidecode(name.upper())
data_analysis.column_aggregation(name)
data_analysis function:
def column_aggregation(name_column):
cursor.execute("""ALTER TABLE simulated_data ADD COLUMN %s""" %
name_column)
cursor.commit()
Once the code is executed, the output is the next error:
cursor.execute("""ALTER TABLE simulated_data ADD COLUMN %s""" %
name_column)
psycopg2.errors.SyntaxError: syntax error at end of input
LINE 1: ALTER TABLE simulated_data ADD COLUMN Eng_temp
Related
I have 2 User models:
User: Default user model:
Account: Custom User model, which is an extension of the defualt user model, as I wanted to add a custom field to it called 'Status'.
The problem is that I wanted to filter the data based on the current User, so id usually do something like:
Account.objects.filter(usernmae = User).values_list('status', flat=True)
The problem is that the Account dataset doesnt have the username but they both have the same ID.
I was thinking of doing something like this:
Status = Account.objects.filter(user_id=User.objects.filter(username = user).values_list('id', flat=True)).values_list('status', flat=True)
But then i get the following error:
I imagine there is a way better way of doing it, if yall could help me out.
Views.py:
def upload_audits(request):
form = audits_form(request.POST or None, request.FILES or None)
if form.is_valid():
form.save()
form = audits_form()
obj = Csv_Audit.objects.get(activated=True)
with open(obj.file_name.path,'r') as f:
#to clear model contents before applying new data
auditsModel.objects.all().delete()
reader = csv.reader(f)
for i,row in enumerate(reader):
if i==0:
pass
else:
user = row[1] # gets data from CSV Table and returns username
Status = Account.objects.filter(user_id = request.user).values_list('status')
auditsModel.objects.create(
qs_login = user,
Status = Status,
)
obj.activated = True
obj.save()
return render(request,"backend/uploads.html",{'form':form})
Accounts.py(Model)
class Account(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
status = models.CharField(('Status'), max_length=200, default='',choices = [('Bau','Bau'),('Week 1','Week 1')])
def __str__(self):
return self.user.username
1 Answer:mahdi rahimi
I tried your method with the following code:
Status = Account.objects.filter(user__username = user).values_list('status', flat=True)
Which resulted in the following error:
And then I thought of doing this:
Status = Account.objects.filter(user = user).values_list('status', flat=True)
But i got this error:
Which actually returns the usernmae but it seems to be asking for an int?
based on my experience, you can simply join the two tables, and get what you want. roughly, it translates to this:
result = Account.objects.filter(user__username = user).values_list('status', flat=True)
or you can do two queries if you are comfortable with that.
found_user_id = User.objects.filter(username = user).values_list('id', flat = True)
result = Account.objects.filter(user_id = found_user_id).values_list('status', flat=True)
hope that helped.
I'm adding articles into a database. That worked fine, except, while the database doesn't let me create duplicates during a session, once I log out and log back in, it does. I didn't want duplicates, so I added these new lines:
maybe_existing_article = Article.query.filter_by(url=article.url)
if (maybe_existing_article):
article = maybe_existing_article.url
return "exists"
But that didn't work, I get "print("article.id=" + str(article.id))
NameError: name 'article' is not defined".
Here is the relevant code, including the new lines.
##############################################
#app.route('/bootstrap', methods=['GET', 'POST'])
def bootstrap():
posted = 1
print ("bootstrap")
global article
if request.method == 'POST':
if not request.form['title'] or not request.form['url'] or not request.form['image_url'] or not request.form['snippet']:
flash('Please enter all the fields', 'error')
else:
article = Article(request.form['title'], request.form['url'], request.form['image_url'],
request.form['snippet'])
maybe_existing_article = Article.query.filter_by(url=article.url)
if (maybe_existing_article):
article = maybe_existing_article.url
return "exists"
else:
db.session.add(article)
try:
db.session.commit()
except exc.SQLAlchemyError:
flash('Article url already exists, failed to post new article')
posted = 0
#return render_template('/error.html', article_url=article.url)
article_list = Article.query.filter_by(url=article.url)
if posted == 1:
flash('Record was successfully added')
else:
db.session.rollback()
article_list = Article.query.filter_by(url=article.url)
article=article_list[0]
print ("article.id=" + str(article.id))
import json
print("a")
return json.dumps(article.id)
else:
print("article.id=" + str(article.id))
urlNumber = str(article.id)
message = {'greeting':urlNumber}
return jsonify(message) # serialize and use JSON headers
And here's the create_tables.py:
article_table = """CREATE TABLE IF NOT EXISTS article (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
url TEXT NOT NULL,
image_url TEXT NOT NULL,
snippet TEXT NOT NULL,
date_upload TEXT DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT article_unq UNIQUE (url)
);"""
You can use an Unique constraint at the table that you want and catch the error when you try to insert a row that was already inserted. In SQLite, you can't add this constraint after the Table is created, so you would need to create the table again.
You can also add an Unique Index to the table that works almost the same:
CREATE UNIQUE INDEX index_name ON table_name(column_name);
If you can't do that, you can always send a SELECT to that table with the ID you are trying to insert and them return an error to the user if it was already inserted, although this is hardly recommended.
i have a database table and i want to filter it by id and update a specific object (column) with an if condition that i have write.
but it get an error:
attributeError: 'int' object has no attribute 'save'
models.py
class Forcast(models.Model):
current_complete = models.FloatField(null=True)
optimestic = models.BooleanField(null=True)
probable = models.BooleanField(null=True)
pessimistic = models.BooleanField(null=True)
optimestic_percentage = models.FloatField(null=True)
probable_percentage = models.FloatField(null=True)
pessimistic_percentage = models.FloatField(null=True)
weight = models.FloatField(null=True)
views.py
def update(request, id):
item = Forcast.objects.get(id=id)
if request.method == 'POST':
form = CharacterNoteForm(request.POST, instance=item)
if form.is_valid():
current_complete = Forcast.objects.values('current_complete').get(id=id)
print(current_complete['current_complete'])
weight = Forcast.objects.values('weight').get(id=id)
print(weight)
optimestic = form.cleaned_data['optimestic']
probable = form.cleaned_data['probable']
pessimistic = form.cleaned_data['pessimistic']
if current_complete['current_complete'] == 65.0 and optimestic:
optimestic_percentagex = current_complete['current_complete'] * weight['weight']
if probable or pessimistic:
probable_percentagey = current_complete['current_complete'] * weight['weight']
pessimistic_percentagez = current_complete['current_complete'] * weight['weight']
obj = Forcast.objects.filter(id=id).update(optimestic_percentage=optimestic_percentagex)
i except that i can update optimestic_percentage with the if condition that i have created.
for more information i am using postgresql
your code looks fine but django framework developed in python it means you can use Pythonic way to find solution for your problems so you can use psycopg2 library to connect your database and update your data
import psycopg2
try:
conncetion = psycopg2.connect(user='db_user',
password='***',
host='192.168.0.0',
port='5432',
database='****')
cursor = conncetion.cursor()
query_update = ''' UPDATE forecast_Table SET optimestic_percentage = ''' + optimestic_percentagex + ''' WHERE id= ''' + id + ''' '''
cursor.execute(query_update)
conncetion.commit()
count = cursor.rowcount
print(count, "Record inserted successfully into forecast table")
except (Exception, psycopg2.Error) as error:
print("Failed to insert record into forecast table", error)
you can use native sql query in django to update your database
With flask_sqlalchemy, I have two tables (A & B) joined together by an association proxy table (C), in which there are some extras fields.
For now with flask_admin I have a ModelView on C, and in this list view I have appended (with the column_formatters option) a link on each item in the related A table column to its details_view page.
It works fine, but I don't know, in this details-view page, how to append a filtered table, based on C, with just the rows relevant to the selected A item.
Ok, I answer to myself here if someone needs it.
I do the opposite by creating another list_view, but for the selected record I want by modifying the index_view method and passing extras params (details) to the template:
class TableCView(admin.ModelView):
list_template = 'modified_listview.html'
#expose('/')
def index_view(self):
self.a_id = request.args.get('id', None)
self._template_args['a_id'] = self.a_id # add more params here
return super(TableCView, self).index_view()
def get_query(self):
# Filter records by a_id
query = super(TableCView, self).get_query()
if self.a_id:
query = query.filter(self.model.a_id == self.a_id)
return query
def get_count_query(self):
query = super(TableCView, self).get_count_query()
if self.a_id:
query = query.filter(self.model.a_id == self.a_id)
return query
Most examples are in the form of finding A in data A to Z.
A DB table does not have a single field from A to Z. When a DB table has several fields together, I want to know the field I'm looking for as a field value and I want to figure out another value with that field value.
For example, searching for a specific name in a DB that contains information from all the students will determine the age.
from Python, Django DB
My data consists of 3 rows:
{title:'1', price:'20'}
{title:'2', price:'30'}
{title:'1', price:'10'}
I want to find title '1' and then return price fileds
Expexted Output:
{title:'1', price:'20'}
{title:'1', price:'10'}
Views.py:
#csrf_exempt
def searching(request):
if request.method == "POST":
parameter = request.POST.get('title')
searchResult = NaverData.objects.filter(Q(title__icontains=parameter)).distinct()
ouput = searchResult
return HttpResponse(ouput)
else:
#GET request
return HttpResponse('GET REQUEST')
Try below code:
searchResult = NaverData.objects.all().filter(title=parameter)
check this
searchresult= NaverData.objects.values("prize").filter(title__exact=parameter)