relation " " does not exist - django

I am creating a project in django using postgresql database. When I run my server the page returns the error
relation "backtest_trade" does not exist
LINE 1: INSERT INTO "backtest_trade" ("pos", "neg", "profit", "trans...
when i try to save my model in the database using back.save(), where back is a variable of the model. I have registered the model in models.py of my app.
I understand that there is no table being created in the database but my understanding is that admin.register should do it. I tried looking up but none of the questions asked was able to help me.
from django.contrib import admin
from django.db import models
from django.contrib.postgres.fields import ArrayField
# Create your models here.
class trade(models.Model):
pos = models.IntegerField(default = 0)
neg = models.IntegerField(default = 0)
profit = models.IntegerField(default = 0)
transaction = ArrayField(models.DecimalField(decimal_places = 3, max_digits= 9,default= 0), default = list)
investment = ArrayField(models.DecimalField(decimal_places = 3, max_digits= 9,default = 0), default = list)
sell = ArrayField(models.DecimalField(decimal_places = 3, max_digits= 9, default = 0), default = list)
entry_date = ArrayField(models.CharField(max_length = 20, default=''), default = list )
exit_date = ArrayField(models.CharField(max_length = 20, default = ''),default = list)
name = models.CharField(max_length = 100, default = "hello")
admin.site.register(trade)
EDIT: I have tried running makemigrations and migrate

I found my error. I had to migrate the particular app in which my model was present.
After running
python manage.py makemigrations backtest
where backtest is the app, I got some error but the table was created in the database

Related

How to update Boolean Value in Flask SQLAlchemy

I am currently using this code
update = user.query.filter_by(uid=id).update(dict(approved=True))
usr.session.commit()
But it gives this as error:
UPDATE
USER MODEL
usr = SQLAlchemy(app)
Class user(usr.Model):
index = usr.Column(usr.Integer(), primary_key=True)
username = usr.Column(usr.String())
uid = usr.Column(usr.String(8))
approved = usr.Column(usr.Boolean(), default=None)
instead of this
update = user.query.filter_by(uid=id).update(dict(approved=True))
Do this
update = user.query.filter_by(uid=id).first()
update.approved = True
usr.session.commit()
This will Solve your Problem

Issue with duplicate values generated when using factory_boy and randint

I'm seeing duplicate values being generated when using randint and factory_boy. My test fails when checking for the asset for each object. The barcode is also the same between the two when calling create() on the factory.
Do I need to provide a different seed before each object creation?
Packages
factory-boy 2.11.1
Faker 1.0.4
python 2.7
django 1.11
Files
seed/factories.py
import factory
from A1.models import *
from random import randint, random
faker = Factory.create()
class AssetFactory(factory.DjangoModelFactory):
class Meta:
model = Asset
asset = "ABC" + str(randint(0000, 9999))
barcode = "AA" + randint(111111, 999999)
user = factory.lazy_attribute(lambda x: faker.name())
tests.py
def test_randomCreation(self):
new_asset = AssetFactory.create()
new_asset2 = AssetFactory.create()
self.assertNotEqual(new_asset.asset, new_asset2.asset) #FAILS
A1/models.py
class Asset(models.Model):
asset = models.CharField(max_length=255, verbose_name="Asset")
barcode = models.CharField(max_length=255)
user = models.CharField(max_length=255)
May someone point me in the right direction?
Thanks in advance!!
The way the Python language is designed, your code cannot work.
It is strictly equivalent to the following:
_RANDOM_ASSET = "ABC" + str(randint(0000, 9999))
_RANDOM_BARCODE = "AA" + str(randint(111111, 999999))
class AssetFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Asset
asset = _RANDOM_ASSET
barcode = _RANDOM_BARCODE
user = factory.LazyAttribute(lambda x: faker.name())
You've fixed a random value for asset and barcode, so every object generated through that factory will have the exact same value.
The proper way would be to use the various built-in declarations:
class AssetFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Asset
asset = factory.fuzzy.FuzzyText(length=4, prefix='ABC', chars=string.digits)
barcode = factory.fuzzy.FuzzyText(length=6, prefix='AA', chars=string.digits)
user = factory.Faker('name')

Shapefile to PostGIS import generates django datetime error

Hi I'm trying to populate the PostGIS database of my Django application using a Shapefile. My models.py is the following :
class Flow(models.Model):
# Primary key
flow_id = models.AutoField("ID, flow identifier", primary_key=True)
# Other attributes
stime = models.DateTimeField("Start time")
stime_bc = models.IntegerField("Year of start time before Christ")
stime_unc = models.DateTimeField("Start time uncertainty")
etime = models.DateTimeField("End time")
etime_bc = models.IntegerField("Year of end time before Christ")
etime_unc = models.DateTimeField("End time uncertainty")
final_vers = models.BooleanField("1 if it's the final version, else 0",
default=False)
com = models.CharField("Comments", max_length=255)
loaddate = models.DateTimeField("Load date, the date the data was entered "
"(in UTC)")
pubdate = models.DateTimeField("Publish date, the date the data become "
"public")
cb_ids = models.ManyToManyField(Bibliographic)
# Foreign key(s)
fissure_id = models.ForeignKey(Fissure, null=True,
related_name='flow_fissure_id',
on_delete=models.CASCADE)
cc_load_id = models.ForeignKey(Contact, null=True,
related_name='flow_cc_id_load',
on_delete=models.CASCADE)
cc_pub_id = models.ForeignKey(Contact, null=True,
related_name='flow_cc_id_pub',
on_delete=models.CASCADE)
# Override default table name
class Meta:
db_table = 'flow'
I want to add the features of my coulees.shp Shapefile into my database (more precisely in the flow table). The attribute table looks like this:
Atribute table
To do so I use the Django Layer Mapping:
import os
from django.contrib.gis.utils import LayerMapping
from .models import Flow
mapping = {'stime':'stime', 'stime_bc':'stime_bc', 'stime_unc':'stime_unc', 'etime':'etime', 'etime_bc':'etime_bc', 'etime_unc':'etime_unc', 'com':'com', 'loaddate':'loaddate', 'pubdate':'pubdate', 'geometry':'geometry'}
shp = os.path.abspath(
os.path.join(os.path.dirname(__file__), 'data', '/home/sysop/Coulees/coulees.shp')
)
def run(verbose=True):
lm = LayerMapping(
Flow, shp, mapping,
transform=True
)
lm.save(verbose=True)
But when I try to run this function I get the following error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/opt/mapobs/mapobs/app/load.py", line 30, in run
transform=True
File "/opt/mapobs/lib/python3.5/site-packages/django/contrib/gis/utils /layermapping.py", line 106, in __init__
self.check_layer()
File "/opt/mapobs/lib/python3.5/site-packages/django/contrib/gis/utils/layermapping.py", line 256, in check_layer
(ogr_field, ogr_field.__name__, fld_name))
django.contrib.gis.utils.layermapping.LayerMapError: OGR field "<class 'django.contrib.gis.gdal.field.OFTDate'>" (of type OFTDate) cannot be mapped to Django DateTimeField.
Unfortunately, I can't find any useful documentation on the internet.

How do i create record with this model

I am trying a record in this table but failed. Please someone show me an example , How do i create a record in this table using ApplicationStage.objects.create(...............)
class ApplicationStage(Base):
stage_id = models.AutoField(primary_key=True)
leave_id = models.ForeignKey(Leave)
auth_id = models.ForeignKey(ApproveAuthority)
approve_status_id = models.ForeignKey(Status)
approve_total_day = models.PositiveIntegerField(default=0)
comment = models.TextField()
approved_time = models.DateTimeField(auto_now_add=True)
is_livedate = models.CharField(choices=(("yes","Yes"),
("no","No"),
),max_length=15)
Navigate to the directory to your application and run:
python manage.py shell
Then import model:
from your_app_name.models import ApplicationStage
Then use the following command to create a record:
a = ApplicationStage(stage_id=1, leave_id=1, auth_id .......... and so on)
a.save()

Trouble writing a "Forwards" for Data Migration in South

So after spending the better part of my day off trying to wrap my head around data and schema migrations in South, I feel like I'm getting close -- but I'm having some trouble with my datamigration forwards function.
For reference, here was my original model:
class Lead_Contact(models.Model):
...
general_notes = models.TextField(blank=True)
...
I'm attempting to migrate to the following:
class Lead_Contact(models.Model):
...
# General_notes has been removed from here...
...
class General_Note(models.Model):
#...and added as a foreign key here.
...
lead_contact = models.ForeignKey('Lead_Contact', null=True, blank=True)
user = models.CharField(max_length=2, choices=USER_CHOICES)
general_date = models.DateField(blank = True, null=True)
general_time = models.TimeField(blank = True, null=True)
general_message = models.TextField(blank=True)
...
I've followed the steps to convert_to_south my app, as well as followed tutorial #3 to add my table, then create my datamigration, and then remove the old Lead_contact.general_notes field in a second schema migration.
The problem is writing my actual Forwards() method; I'm attempting to write out the data from the old general_notes field into the General_Note table:
class Migration(DataMigration):
def forwards(self, orm):
for doctor in orm.Lead_Contact.objects.all():
orm.General_Note.objects.create(lead_contact=doctor.id, user = "AU", general_date = "2011-03-12", general_time = "09:00:00", general_message = doctor.general_notes)
def backwards(self, orm):
for note in orm.General_Note.objects.all():
new_gn = orm.Lead_Contact.objects.get(id=note.lead_contact)
new_gn.general_notes = note.general_message
new_gn.save()
For reference, I'm using django 1.2, south 0.7, and MySql 5.0.51a.
Edit: Removed the Try/Except bits, and the error message I'm getting is: "ValueError: Cannot assign "158L": "General_Note.lead_contact" must be a "Lead_Contact" instance.
Shouldn't tying General_Note.lead_contact to Doctor.id be an appropriate Lead_Contact instance?
Try changing doctor.id to doctor:
orm.General_Note.objects.create(lead_contact=doctor.id,
user = "AU",
general_date = "2011-03-12",
general_time = "09:00:00",
general_message = doctor.general_notes)
To:
orm.General_Note.objects.create(lead_contact=doctor,
user = "AU",
general_date = "2011-03-12",
general_time = "09:00:00",
general_message = doctor.general_notes)