Accessing rowset after committing a transaction - django

I have a problem with django and msssql (stored procedure):
com_error at /add_client/
(-2147352567, 'Ocurri\xf3 una excepci\xf3n.', (0, u'Microsoft SQL Server Native
Client 10.0', u'The object is in a zombie state. An object may enter a zombie
state when either ITransaction::Commit or ITransaction::Abort is called, or when a
storage object was created and not yet released.', None, 0, -2147418113), None)
Stored Procedure:
ALTER PROCEDURE [dbo].[InsertPerson](
#first_name nvarchar(80),
#last_name nvarchar(80),
#dni nvarchar(10),
#sex nvarchar(2),
#phone_number nvarchar(10),
#cellular_number nvarchar(9),
#email nvarchar(50),
#bank_account nvarchar(25),
#department nvarchar(50),
#province nvarchar(50),
#district nvarchar(50),
#address nvarchar(50),
#description nvarchar(128),
#is_active nvarchar(2),
#creation_time bigint)
AS
SET NOCOUNT ON
INSERT INTO persons (first_name, last_name, dni, sex, phone_number, cellular_number,
email, bank_account, department, province, district, address, description, is_active,
creation_time)
VALUES(#first_name, #last_name, #dni, #sex, #phone_number, #cellular_number, #email,
#bank_account, #department, #province, #district, #address, #description, #is_active,
#creation_time)
SELECT ##IDENTITY AS person_id
SET NOCOUNT OFF
This procedure is working perfect, but the problem is when Accessing rowset after committing a transaction (get the insert id).
My view in Django is:
from django.db import transaction
...
#transaction.commit_manually
def add_client(request):
...
...
...
description = request.POST.get('description', '')
is_active = request.POST.get('is_active', '')
cursor = connection.cursor()
cursor.callproc("InsertPerson", (first_name, last_name, dni, sex, phone_number, cellular_number, email, bank_account, department, province, district, address, description,
is_active, creation_time))
connection.commit()
row = cursor.fetchone()
return HttpResponse(json.dumps({"mensaje": row.person_id}), content_type='application/json')

Related

How to insert multiple foreign key values in django?

i've tried using bulk_create but i couldn't insert the foreign key value, i want to add 100 bikes with about 20 stations
class Bike(models.Model):
ID_Bike = models.CharField(primary_key=True, max_length=120)
Belong_Station = models.ForeignKey(
Station, on_delete=models.CASCADE, related_name='listBike')
def __str__(self):
return self.ID_Bike
class Station(models.Model):
name_Station = models.CharField(max_length=120)
latitude = models.FloatField(max_length=120)
longitude = models.FloatField(max_length=120)
address = models.CharField(max_length=120, default="")
def __str__(self):
return self.name_Station
You should check out fixtures. If I were you, I would stick with the SQL though. This is how an insert statement that will insert two Station and three Bike records could look like.
insert into Station (id, name_Station, latitude, longitude, address) values (1, "Johns Garage", 41.12, 23.58, "Fast Road 25, 001 12 Wales") , (2, "Mike riders place", 42.56, 21.43, "Somewhere street 12");
insert into Bike (ID_Bike, Belong_Station) values ("Johns bike", 1), ("Johns second bike", 1), ("Mikes bike", 2);
Notice that you must first insert Station records. Otherwise the foreign key constraint will fail if you try to insert Bikes first.

Flask / Automatic Database field change on True depending on the date

How to make expired default in False and automatic setting of the expired to True, depending on whether the date has passed from the field expire_date?
My model.py
class PlanPurchase(db.Model):
plan_id = db.Column(db.Integer, db.ForeignKey('plan.plan_id'))
user_id = db.Column(db.Integer, db.ForeignKey('user.user_id', ondelete='CASCADE'))
expire_date = db.Column(db.DateTime)
expired = db.Column(db.Boolean)
def __init__(self, plan_id, user_id, expire_date, total_cost=0, expired=True):
self.plan_id = plan_id
self.user_id = user_id
self.expire_date = expire_date
self.expired = expired
Example.
expire_date = 2020-02-02 . expired should be True.
expire_date = 2020-12-12 . expired should be False.
It should be automatic. Compare current date and date in expire_date
There are two approaches for this.
If you have some kind of login system and user has to login to interact with PlanPurchase, then you can use before_request flask decorator to check for expiration and update the field. The before_requestcallback is always run before your actual endpoint request.
#app.before_request
def before_request_func():
if session.get('logged_in'):
""""
Check for expiration
and update expire field accordingly.
"""
#app.route("/login")
def login():
"""
Your login logic goes here.
"""
session['logged_in'] = True
You can use background task like celery or even configure cron jobs to check for expiration logic every midnight and update accordingly.
It depends upon your application architecture on which method you should use.
Tip:
Seems like you are using flask_sqlalchemy. You don't need the __init__ to pass parameters to the DB model. You can discard it.
class PlanPurchase(db.Model):
plan_id = db.Column(db.Integer, db.ForeignKey('plan.plan_id'))
user_id = db.Column(db.Integer, db.ForeignKey('user.user_id', ondelete='CASCADE'))
expire_date = db.Column(db.DateTime)
expired = db.Column(db.Boolean)
purhcase = PlanPurchase(plan_id=1,user_id=1,expired_date=datetime.now(),expired=False)
The above code works fine.

Return value of related object with condition

As for example I've got 3 models: User, Event, Participator
class Event(..):
creator = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='event_creator_set')
class Participator(..):
status = models.CharField(..)
event = models.ForeignKey('events.Event', on_delete=models.CASCADE, related_name='participators_set')
user = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='participations_set')
I want to get all user's and also get information about relation with specific event. If user is even't participator -> return status from Participator models, else -> null
Here is my queries:
e = Event.objects.first()
users = User.objects.annotate(is_participationg=Case(When(id__in=e.participators_set.values_list('user__id', flat=True), then=Value(True)), default=Value(False), output_field=BooleanField()))
So I can know whether user is participating in specific event. How can I get user's participating status in then and None in default?
I think you make things too complicated, you know the id of the event, so you can filter like:
from django.db.models import Case, CharField, F, Max, Value, When
User.objects.annotate(
participation_status=Max(Case(
When(participations_set__event=e, then=F('participations_set__status')),
default=Value(None),
output_field=CharField()
))
)
This then results in the query:
SELECT user.*,
MAX(CASE WHEN participator.event_id = 123
THEN participator.status
ELSE NULL END
) AS participation_status
FROM user
LEFT OUTER JOIN participator ON (user.id = participator.user_id)
GROUP BY user.id
(with 123 in reality the primary key of e).
In case the User participated in the event in multiple ways, the lexicographical maximum status will be used.

Grouping by multiple columns in Django

I have a model with a few columns:
Model (id, country, city, name, age)
I need to group and sort by a few columns:
SELECT * FROM Model
WHERE country = 'USA'
GROUP BY id, city, age
ORDER BY id, city, age
and I'd like to query the same with Django ORM.
Model.objects.filter(country='USA').group_by('id', 'city', 'age').order_by('id', 'city', 'age')
But this call throws after group_by as it returns None.

Message Online Friends

FQL Query
SELECT name, online_presence IN ('active', 'idle') FROM user WHERE online_presence IN ('active', 'idle') AND uid in(SELECT uid2 from friend where uid1= me())
By This Query I am getting friends
Please Anyone Tell Me how can I message these online friends.
Method 1:
Assume:
Your app id is "87741124305"
"4" is one of your friend uid get from FQL query:
SELECT uid, name, online_presence FROM user WHERE online_presence IN
('active', 'idle') AND uid in(SELECT uid2 from friend where uid1=
me())
you want to share a link "https://www.youtube.com/watch?v=VM56POaEEX4"
https://www.youtube.com/facebook_redirect is your app CANVAS_URL
The full link would be:
https://www.facebook.com/dialog/send?app_id=87741124305&to=4&link=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DVM56POaEEX4%26feature%3Dshare&redirect_uri=https%3A%2F%2Fwww.youtube.com%2Ffacebook_redirect
Method 2:
Send email to him.The email address is in the form USERNAME#facebook.com You can get the USERNAME via FQL query:
SELECT uid, username, online_presence FROM user WHERE online_presence
IN ('active', 'idle') AND uid in(SELECT uid2 from friend where uid1=
me())
Please note that, some user doesn't have username. Also, you can't send empty body message.
Method 3:
You may refer to https://developers.facebook.com/docs/chat/ for Jabber/XMPP service.