if is_admin == True:
admin_users = Group(name = 'Admin')
try:
admin_users.save()
except:
log.info("Admin Group already exists")
pass
group_id = Group.objects.get(name='Admin').id
If in the data that I get 'is_admin' is true then I will create the group 'Admin' if not existed then save it and fetches the id of that group-'Admin'. This id will be saved in the userinfo with Group as a foreign key.
The following query should give me the id of that group.
group_id = Group.objects.get(name='admin').id
Instead it is saying
current transaction is aborted, commands ignored until end of transaction block
I am using the postgresql database I don't know why it is giving me the error while executing this query. Please tell me how to write the query.
What are you trying to achieve is already in django: get_or_create. Using this your code should look like
group, created = Group.objects.get_or_create(name='Admin')
if created:
log.info("Admin Group already exists")
group_id = group.pk
pk is a convenience property on all django models that always point to a primary key field, no matter if it's autocreated or specified explicitly.
Related
I am in the process of bulk adding objects to my database on the condition that it
a) doesn't already exist in my database
b) isn't already in the process of being created (because the data i'm working with could have duplicate results given to me)
Previously, to handle step b, I was storing the "to-be-created" objects in a list, and iterating through it to check if there was a matching object, but I stumbled upon sets and figured that I could just run the `.add` method on the set and know that the collection was being deduped for me.
I'm testing with a fresh database, so I know my issue exists in the process of step b.
My code looks something like
new_owners = set()
for item in items:
owner = Owner.find_owner_by_id(item['owner']['id'])
if owner is None:
owner = Owner(owner_id=item['owner']['id'], display_name=item['owner']['display_name'])
new_owners.add(owner)
# print to check deduped set of owners
for owner in new_owners:
print(f'{owner.display_name} | {owner.owner_id}')
db.session.add_all(new_owners)
db.session.commit()
Owner.py
#dataclass()
class Owner(db.Model):
__tablename__ = 'owner'
id = Column(Integer, primary_key=True)
owner_id = Column(String(40), unique=True)
display_name = Column(String(128), nullable=False)
def __eq__(self, other):
return self.owner_id == other.owner_id
def __hash__(self):
return hash(self.owner_id)
I'm not sure what I am missing at this point, because my `print` check before adding the objects to the database session doesn't show any duplicate objects, but somehow I still get this unique constraint error.
[SQL: INSERT INTO owner (owner_id, display_name) VALUES (?, ?)]
[parameters: ('yle42kxojqswhkwj77bb34g7x', 'RealBrhaka')]
Which would only happen if this object was in the given data more than once, but I would expect the set to handle deduping this
I have created a flask application and using mysql as DB backend and this is used by multiple users simultaneously.
The problem I'm having is,In my homepage a select query is performed and data is displayed to the user but same data is showing to all users.it should be unique. I have tried to lock the row by using FOR UPDATE while selecting the row. I know that I'm not updating the row,so the transaction will be closed when the function ends and the row will be released from lock.
How to overcome this problem?
Expected output: Each user should get different data from the table.(Even when they refresh)
#is_logged_in
#app.route('/')
def index():
conn = mysql.connection
cur = conn.cursor()
cur.execute("select mylist ,myurl ,swatch,parent from image_links where status =%s LIMIT 1 FOR UPDATE",("fetched",))
parent = cur.fetchall()
for row in parent:
mylistitems = row[0].split(",")
swatches = row[2].split(",")
myurlsitems = row[1].split(",")
pid = row[3]
if asinlist != ['']:
merged = tuple(zip(mylistitems ,myurlsitems ,swatches))
return render_template('home.html',firstimage= myurlsitems[0],merged=merged)
else:
cur.execute("UPDATE asin_links SET status = %s WHERE pid= %s", ("invalid",pid,))
conn.commit()
return redirect(url_for('index'))
I can't see any "current user" specific parameters used in your sql query or any data filtering decided on some user ID.
Basically, if you are running the same code, same query for all requests on this endpoint, it will never be really unique. You need to add some user specific checks so you can differentiate the output for the current requesting user.
Depending on your use-case and database models, if the data in the table image_links is also created/inserted by some user action you might want additionally save some user ID alongside these values, eg. by extending the table model with another "user_id" column and on insert also add the id of the current user.
You are using some auth decorator #is_logged_in, if you are already handling users in some table then the another user_id column could be a reference to the respective user's primary key. Then, in your example, you would just add additional where user_id = check with the current user's primary key.
As I see in this SQL query:
SELECT mylist, myurl, swatch, parent FROM image_links WHERE status
perhaps you did specify the related user to get its own specific data, try to replace that last "where" with:
WHERE id = (user.id) --> user object
or you could use the AND keyword, something like
WHERE status = (x) AND id = (y)
My constrains method not working for id_number. can't figure it out why.
from odoo import models, fields, api
from odoo.exceptions import ValidationError
class KindeGarden(models.Model):
_inherits = {'res.partner': 'partner_id'}
_name = 'kindergarten.model'
_description = 'Kindergarten'
age = fields.Integer(string="Amžius", required=False, default="1")
group = fields.Char(string="Grupė", compute="_compute_group", store=True)
height = fields.Float(string="Ūgis", required=False)
weight = fields.Float(string="Svoris", required=False)
id_number = fields.Integer(string="Registravimo Nr", required=True)
#api.constrains('id_number')
def _check_id_number_field(self):
for i in self:
if i.id_number < 10:
raise ValidationError("Number is to small")
and i'm also having this
WARNING -Kindegarden odoo.models.schema: Table 'kindergarten_model': unable to set a NOT NULL constraint on column 'id_number' !
If you want to have it, you should update the records and execute manually:
ALTER TABLE kindergarten_model ALTER COLUMN id_number SET NOT NULL
Like mentioned above, it looks like it is some data are null already before you set required parameter to true.
odoo has a shell you can use to access your DB if you are not familiar with SQL.
odoo-bin -d <database_name> shell
inside the shell, do as follow so you will see.
>> records = env['kindergarten.model'].search([('id_number','=',False)])
>> len(records)
if it returns a number aside from 0, it means that those are NULL value. so do like.
>> for record in records:
record.write({'id_number': 0.0})
>>env.cr.commit()
Then update your module again.
If this doesn't work you will need to do it manually with SQL.
Did you add constraint after few records were added ?
The error you got generally comes when postgres is unable to set "NOT NULL" to the column because it already has null values
class PersonSite(models.Model):
vps_id = models.AutoField(primary_key=True)
person = models.ForeignKey(CanonPerson, db_column='p_id',null=True)
site = models.ForeignKey(CanonSite, db_column='s_id',null=True)
person_sites = PersonSite.objects.filter(person=cp)
for person_site in person_sites:
if person_site and person_site.site_id and person_site.site.s_id:
# crashes for some records
We have a problem with the data, where PersonSite may point to a site that no longer exists.
In the debugger I can see that person_site.site_id has a value of 5579, however that id doesn't exist in the database:
select * from tbl_vpd_sites where s_id = 5579
Hence person_site.site_id is not null, yet just accessing person_site.site within the conditional crashes the app with the message:
DoesNotExist: CanonSite matching query does not exist.
This is a very difficult situation, I can't even check for this case to bypass it.
PersonSite.site has null=True, so it makes sense that you have to check if a object exists before accessing it.
In stead of doing all those checks if person_site and person_site.site_id and person_site.site.s_id: you can just query the db and filter the empty sites out.
person_sites = PersonSite.objects.filter(person=cp).filter(site__isnull=False)
This will return only the PersonSite objects where site IS NOT NULL and therefore have a pk.
I am using sql alchemy in my project.
I have one problem when two or more tables are joined or have foreign key relation then i am unable to query on joined tables attribute in where condition.
Eg. I have notice table and a user table user.id is foreign key of notice.sender
now I want to search notice by user.name
notice table:[id, sender(FK user.id), receiver(FK user.id), subject, message, status]
user table: [id, name, email, address, status]
Join in notice model:
sender_user = relationship('User', primaryjoin='Notice.sender==user.id', backref=backref("sender_user"))
receiver_user = relationship('User', primaryjoin='Notice.receiver==user.id', backref=backref("receiver_user"))
SQL alchemy filter query:
user_name='john'
notice=db_session.query(Notice)
notice = notice.filter(Notice.sender_user.name == user_name)
Following query doesn't works:
notice=db_session.query(Notice)
notice = notice.filter(Notice.user.name == user_name)
Please help!
You need to acquire a session object, then do:
query = session.query(Notice).filter(Notice.sender_user.name == user_name)
results = query.all()
If that does not work (you don't get the results you expect), try doing this:
session.query(Notice, User.name).filter((Notice.sender_user.id == User.id) & (User.name == user_name))
results = query.all()
I suppose you also have a field called sender which is the id of the user. Then, this should also work:
session.query(Notice, User.name).filter((Notice.sender == User.id) & (User.name == user_name))
Retry all of them, I made some small modifications. (you can see them in revision history). It would be weird if they don't work... (If they don't, try posting the question on the SQLAlchemy mailing list)