I am currently trying to save a Django object. My code looks like this
boxscore = BoxScore.objects.create(**defaults)
print(defaults)
input(boxscore)
Here's the output:
{'away_first': 0, 'away_second': 6, 'away_third': 7, 'away_fourth': 17, 'away_final': 30, 'home_first': 0, 'home_second': 7, 'home_third': 0, 'home_fourth': 7, 'home_final': 14}
BoxScore object (190)
Here's my admin:
#admin.register(BoxScore)
class BoxScoreAdmin(ImportExportModelAdmin):
pass
Here's the model:
class BoxScore(Base):
home_final = models.IntegerField()
away_final = models.IntegerField()
home_first = models.IntegerField()
away_first = models.IntegerField()
home_second = models.IntegerField()
away_second = models.IntegerField()
home_third = models.IntegerField()
away_third = models.IntegerField()
home_fourth = models.IntegerField()
away_fourth = models.IntegerField()
home_ot = models.IntegerField(null=True)
away_ot = models.IntegerField(null=True)
Here's the whole helper function if that is relevant.
def create_boxscore(df):
defaults = {
'away_first': int(df.at[0, '1']),
'away_second': int(df.at[0, '2']),
'away_third': int(df.at[0, '3']),
'away_fourth': int(df.at[0, '4']),
'away_final': int(df.at[0, 'Final']),
'home_first': int(df.at[1, '1']),
'home_second': int(df.at[1, '2']),
'home_third': int(df.at[1, '3']),
'home_fourth': int(df.at[1, '4']),
'home_final': int(df.at[1, 'Final']),
}
try:
defaults['home_ot'] = int(df.at[1, 'OT'])
defaults['away_ot'] = int(df.at[0, 'OT'])
except:
pass
boxscore = BoxScore(**defaults)
boxscore.save()
return boxscore
However, nothing is showing in Django admin as being saved in the database. Why would this be and how do I fix it?
Update: I queried the database and confirmed nothing is being saved so it is not a Django admin display issue.
Update 2: If I run the sample above separately, it saves fine. However, if it is run within a helper function, nothing saves. Does being in a helper function cause saving difficulties?
Update 3: In the main function, I ran this line of code and nothing was saved:
if 'Final' in dfs[i].columns and '4' in dfs[i].columns:
defaults = {'away_first': 0, 'away_second': 6, 'away_third': 7,
'away_fourth': 17, 'away_final': 30, 'home_first': 0, 'home_second': 7,
'home_third': 0, 'home_fourth': 7, 'home_final': 14}
boxscore = BoxScore.objects.create(**defaults)
input(boxscore)
But this was still outputted so I know it's reaching that line of code:
BoxScore object (200)
Related
Hi I want service old book sale service for university student
I create ItemPost model and when user post their books, ItemPost's deadline saved in deadline
from django.db import models
from django.conf import settings
from django.utils import timezone
def localtime():
return timezone.localtime(timezone.now())
class ItemPost(models.Model):
title = models.TextField(
)
created_at = models.DateTimeField(
default=localtime
)
is_deleted = models.BooleanField(
default=False,
verbose_name="삭제된 포스트",
)
# 마감날짜를 구하는 함수
def deadline_def(self):
year_of_item_created = self.created_at.year
if self.created_at.month <= 6:
return timezone.datetime(year_of_item_created, 6, 30)
else:
return timezone.datetime(year_of_item_created, 12, 31)
deadline = property(deadline_def)
# 등록된 학기가 끝난 포스트인지 확인
def is_ended_semester_def(self):
now = timezone.now()
if now > self.deadline:
return True
return False
is_ended_semester = property(is_ended_semester_def)
def __str__(self):
return self.title
I want compare item's deadline, timezone.now()
and return True or False
but I can't if I command item.is_ended_semester
TypeError: can't compare offset-naive and offset-aware datetimes
how can i solved this problem?
item.deadline
> datetime.datetime(2017, 6, 30, 0, 0)
timezone.now()
> datetime.datetime(2017, 7, 14, 8, 50, 57, 91304, tzinfo=<UTC>)
I solved my problem, using timezone.utc
# 마감날짜를 구하는 함수
def deadline_def(self):
year_of_item_created = self.created_at.year
if self.created_at.month <= 6:
return timezone.datetime(year_of_item_created, 6, 30, tzinfo=timezone.utc)
else:
return timezone.datetime(year_of_item_created, 12, 31, tzinfo=timezone.utc)
On my Django site, I am saving a user's reactions so when a user clicks a button, I store it as a created time and when the user clicks it second time, I stored the time as a finish time and so forth. Here it is my model;
class UserStatus(models.Model):
STATUS_TYPES = (
('online', 'online'),
('offline', 'offline')
)
user = models.ForeignKey(User)
status_type = models.CharField(max_length=30, choices=STATUS_TYPES, default='online')
created_time = models.DateTimeField(auto_now_add=True)
finish_time = models.DateTimeField(blank=True, null=True)
time_diff = models.DateTimeField(blank=True, null=True)
I added time_diff to show the time difference between created_time and finish time. When I try an example in the shell, I use;
user_status.created_time
datetime.datetime(2016, 3, 31, 12, 50, 21, tzinfo=<UTC>)
user_status.finish_time
datetime.datetime(2016, 3, 31, 12, 51, 37, 998593, tzinfo=<UTC>)
user_status.finish_time - user_status.created_time
datetime.timedelta(0, 76, 998593)
Everything seems to be fine until now, however when I wrote user_status.save() it gave an error;
line 93, in parse_datetime
match = datetime_re.match(value)
TypeError: expected string or buffer
I did not understand why it gave such an error.
Thank you in advance.
Now you try to use DateTimeField, but this field can only be used for storing date and time (but not time difference). You should use DurationField for storing timedelta.
I have 2 models (sqlalchemy 0.9) which references to each other (simplified and with integers as id)
class Device(SyncableModel):
__tablename__ = 'devices'
...
id = db.Column(db.Integer, primary_key=True)
current_program_id = db.Column(db.Integer, db.ForeignKey('programs.id', use_alter=True, name='fk_current_program'))
current_program = relationship(
'Program', backref = backref('current_for_device', uselist=False),
primaryjoin="Device.current_program_id==Program.id",
post_update=True
)
programs = relationship(
'Program', backref='device', lazy='joined',
cascade="all, delete-orphan",
primaryjoin="Device.id==Program.device_id"
)
class Program(SyncableModel):
__tablename__ = 'programs'
...
id = db.Column(db.Integer, primary_key=True)
device_id = db.Column(db.Integer, db.ForeignKey('devices.id', ondelete='CASCADE'))
name = db.Column(db.String(64))
And i need to make this:
device = Device()
device.id = 1
program = Program()
program.id = 2
program.device_id = device.id
device.current_program_id = program.id
db.session.add_all([device, program,])
db.session.commit()
But i'm getting:
IntegrityError: (IntegrityError) (1452, 'Cannot add or update a child row: a foreign key constraint fails (`cloud2`.`devices`, CONSTRAINT `fk_current_program` FOREIGN KEY (`current_program_id`) REFERENCES `programs` (`id`))') 'UPDATE devices SET created=%s, updated=%s, name=%s, rain_detected=%s, current_program_id=%s, timezone=%s, synced=%s WHERE devices.id = %s' (datetime.datetime(2015, 8, 11, 19, 48, 23), datetime.datetime(2015, 8, 11, 19, 48, 26), 'nWhosie', 0, '\xeaL\xff\x80\xe5\xffC2\x9a)\xe5\x86\xe4\xad}l', 'America/Chicago', datetime.datetime(2015, 8, 11, 19, 48, 27), '\xd4\xe3\x04;:\xa0M\xce\x95\x9a\xf9U\x05x"\x10')
Note: i'm using not int ids in real
I thought that with post_update=True it will work as expected. What am i doing wrong?
Thanks!
Update
As #gsb-eng mentioned the root of the problem should be in missing explicit relationship setting. But it is a problem as objects are generated from list of dicts and it would be hard to find out all relations.
Update 2
Finally i was able to fix relationships with the help of inspect:
def fix_relationships(objs):
for obj in objs:
insp = inspect(type(obj))
for relation in insp.relationships:
if relation.post_update:
# A relation to be set
relation_key = relation.key
if getattr(obj, relation_key):
# Relation had already been set
continue
foreign_key = relation.primaryjoin.left.key
target_class_name = relation.argument.arg
target_key = relation.primaryjoin.right.key
fk = getattr(obj, foreign_key)
if not fk:
# Nothing to set.
continue
for o in objs:
if o.__class__.__name__ == target_class_name \
and getattr(o, target_key) == fk:
setattr(obj, relation_key, o)
setattr(obj, foreign_key, None)
break
As I observed your below error it is trying to insert this value for our program current_program_id='\xeaL\xff\x80\xe5\xffC2\x9a)\xe5\x86\xe4\xad}l', and that should be an integer value as it defined.
UPDATE devices SET created=%s, updated=%s, name=%s, rain_detected=%s, current_program_id=%s, timezone=%s, synced=%s WHERE devices.id = %s' (datetime.datetime(2015, 8, 11, 19, 48, 23), datetime.datetime(2015, 8, 11, 19, 48, 26), 'nWhosie', 0, '\xeaL\xff\x80\xe5\xffC2\x9a)\xe5\x86\xe4\xad}l', 'America/Chicago', datetime.datetime(2015, 8, 11, 19, 48, 27), '\xd4\xe3\x04;:\xa0M\xce\x95\x9a\xf9U\x05x"\x10')
Ideally it shouldn't fire the UPDATE query since you didn't mention the relationship, device.current_program = program defines the actual relationship between those two objects.May you better try running this....
device = Device()
device.id = 1
program = Program()
program.id = 2
device.current_program = program
device.programs = [program]
db.session.add_all([device, program,])
db.session.commit()
Using django model with Foreignkey as follows:
class Types_of_Expenditures(models.Model):
Expenditure_owner = models.CharField(default="None",max_length=50)
Expenditure_Type = models.CharField(default="Miscellaneous",max_length=50)
Expenditure_Type_Description = models.CharField(max_length=200)
def __unicode__(self):
return self.Expenditure_Type
class Expenditure(models.Model):
exp_owner= models.CharField(default='None',max_length=50)
exp_date = models.DateTimeField("Expenditure_Date")
description = models.CharField(max_length=1000)
amount = models.FloatField(default=0)
currency = models.CharField(max_length=15,default="MYR",editable=True)
exp_pocket = models.ForeignKey(Pockets, null=True, blank=True)
exp_type = models.ForeignKey(Types_of_Expenditures)
class Meta:
unique_together = ('exp_date', 'description',)
def __unicode__(self):
return self.description
Now when i save data in Types of expenditure i am doing :
Types_of_Expenditures.objects.get_or_create(Expenditure_owner='a',Expenditure_Type_Description="Default one")
and in database data is as :
id Expenditure_owner Expenditure_Type Expenditure_type_description
1 a Miscellaneous default one
but when i add anything to Expenditure data is saved with data in exp_type as 1 but it should be Miscellaneous because in def unicode i am returning Expenditure_type .
Here s how i am using formset to save data for Expenditure model:
ExpFormSet = modelformset_factory(Expenditure,extra=10,max_num=10,
fields=('exp_date', 'description','exp_type','amount','currency','exp_pocket'),
can_delete=False,form=ExpenditureForm)
if request.method == 'POST':
formset = ExpFormSet(request.POST,queryset=Expenditure.objects.filter(exp_owner=request.user))
if formset.is_valid():
print "printing formset",formset
formset.save(commit=True)
cd = form.cleaned_data
expenditureType = cd.get('exp_type')
print "Expenditure Type entered is ",expenditureType
return index(request)
What i am doing in index view:
Expenditure_list = Expenditure.objects.order_by('-exp_date').filter(exp_owner=request.user)
print "Expenditure List is : ", Expenditure_list.values_list()
Now output of this expenditure view as value of Expenditure_list.values_list() is (please see last value which is 1 i.e. value of exp_type ) :
Expenditure List is : [(3, u'a', datetime.datetime(2014, 9, 12, 15, 32, 10), u'test', 1.0, u'MYR', u'pocket', 1)]
What do i expect :
Expenditure List is : [(3, u'a', datetime.datetime(2014, 9, 12, 15, 32, 10), u'test', 1.0, u'MYR', u'pocket', u'Miscellaneous')]
Can anyone help what could be the problem here ?
I feel This question might be wrong may be it will save only foreign key there i.e. id and in order to get expenditure type i need to retrieve it using Types_of_Expenditure.objects.get(pk="Key as in list")
but not sure if there s an alternate way ?
I think I understand your question. You seem to be expecting values_list to return the __unicode__ of a related model, but there's no reason to think it would: as the name implies, it returns the values only, and the value of a ForeignKey field is just the ID.
You can supply a list of fieldnames to values_list and traverse the relationship there, if you want:
Expenditure.objects.values_list('description', 'amount', 'exp_type__ Expenditure_Type')
I'd like to make an application that allows me to reserve an item during a specified period.
I need a function to check if the specified item is already booked during the period i want to use it (so the booking should fail). Can you help me?
models.py
from django.db import models
from datetime import *
from django.db.models import Q
import datetime
from django.core.exceptions import ValidationError
class Reservation(models.Model):
date_debut = models.DateTimeField('debut de la reservation')
date_fin = models.DateTimeField('fin de la reservation')
obj_res = models.ForeignKey('Materiel')
notice = models.CharField(max_length=200)
personne = models.ForeignKey('Personne')
def __int__(self):
return self.id
def save(self, *args, **kwargs):
new_start_date = datetime.datetime(2013, 11, 16, 10, 00)
new_end_date = datetime.datetime(2013, 11, 16, 11, 00)
material = Materiel.objects.get(nom="Bimaire 1")
clashing_reservations = Reservation.objects.filter(obj_res=material).filter(
Q(date_debut__lte=new_start_date, date_fin__gte=new_start_date) |
Q(date_debut__lt=new_end_date, date_fin__gte=new_end_date)
)
if clashing_reservations.exists():
raise ValidationError('Those dates clash with another reservation.')
return super(Reservation, self).save(*args, **kwargs)
class Materiel(models.Model):
nom = models.CharField(max_length=200)
description = models.CharField(max_length=200)
responsable = models.CharField(max_length=200)
modalites = models.CharField(max_length=200)
def __unicode__(self):
return self.nom
class Personne(models.Model):
nom = models.CharField(max_length=200)
prenom = models.CharField(max_length=200)
def __unicode__(self):
return self.nom
views.py
def reservation(request):
if request.POST:
form = ReservationForm(request.POST, request.FILES)
if form.is_valid():
form.save()
else:
form = ReservationForm()
args = {}
args.update(csrf(request))
args["form"] = form
return render_to_response("reservation.html", args)
EDIT
Thanks so far it's seems to work.
But now i want define that new_start_date and new_end_date are the actual values of the form.
This is untested code, but I believe that this logic should test whether any other reservations overlap the one submitted in the form. This should probably be put in a clean method of the form, or some other validation. Perhaps even on the save method of the Reservation model:
from django.db.models import Q
new_start_date = datetime.datetime(2013, 11, 16, 10, 00)
new_end_date = datetime.datetime(2013, 11, 16, 11, 00)
material = Materiel.objects.get(nom='Whatever')
clashing_reservations = Reservation.objects.filter(objet=material).filter(
Q(date_debut__lte=new_start_date, date_fin__gte=new_start_date) |
Q(date_debut__lt=new_end_date, date_fin_gte=new_end_date)
)
if clashing_reservations.exists():
raise ValidationError('Those dates clash with another reservation.')
I don't know the format your dates are in but regardless you can use the module datetime to compare (subtract, add, higher/lower etc.) dates and times with one another.
So I've made a simple example to illustrate its use (I presume your format is months/days/years):
from datetime import *
debut_date = datetime.strptime(date_debut_db, "%m/%d/%y")
fin_date = datetime.strptime(date_fin_db, "%m/%d/%y")
debut_date2 = datetime.strptime(date_debut_form, "%m/%d/%y")
fin_date2 = datetime.strptime(date_fin_form, "%m/%d/%y")
if (debut_date2 > debut_date and debut_date2 < fin_date) or (fin_date2 > debut_date and fin_date2 < fin_date):
print "Impossible!"
else:
print "Possible!"
date_debut_db and date_fin_db are the dates you get out of your database whereas date_debut_form and date_fin_form are the ones that the user fills in.