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()
Related
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
I am using Django 2.0.
I have the the following models:
class SingleMeasurements (models.Model):
MASS = 'kg'
VOLUME = 'ltr'
PIECES = 'pcs'
MUNITS_CHOICES = (
(VOLUME, 'Liter'),
(MASS, 'Kilogram'),
(PIECES, 'Pieces'),
)
name = models.CharField(max_length=200,unique=True,null=False)
slug = models.SlugField(unique=True)
formtype = models.CharField(max_length=10,choices=MUNITS_CHOICES,verbose_name="Units")
quantity = models.DecimalField(max_digits=19, decimal_places=10)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
class Recipe(models.Model):
MASS = 'kg'
VOLUME = 'ltr'
PIECES = 'pcs'
MUNITS_CHOICES = (
(MASS, 'Mass'),
(VOLUME, 'Volume'),
(PIECES, 'Pieces'),
)
name = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
tags = models.ManyToManyField(Tag,related_name='recipes_recipe_tag',blank=True)
primary_unit = models.CharField(max_length=10,choices=MUNITS_CHOICES,default=VOLUME,verbose_name="Preferred Display Units",null=True,blank=True)
mass_unit = models.ForeignKey(SingleMeasurements,on_delete=models.PROTECT,related_name='recipe_singlemeasurement_mass_unit',blank=True,null=True)
mass_quantity = models.DecimalField(max_digits=19, decimal_places=10,null=True,blank=True)
volume_unit = models.ForeignKey(SingleMeasurements,on_delete=models.PROTECT,related_name='recipe_singlemeasurement_volume_unit',blank=True,null=True)
volume_quantity = models.DecimalField(max_digits=19, decimal_places=10,null=True,blank=True)
pieces_unit = models.ForeignKey(SingleMeasurements,on_delete=models.PROTECT,related_name='recipe_singlemeasurement_pieces_unit',blank=True,null=True)
pieces_quantity = models.DecimalField(max_digits=19, decimal_places=10,null=True,blank=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
I have opened Django shell by the following command:
python manage.py shell_plus --print-sql --ipython
I am trying to run the following command
Recipe.objects.select_related('mass_unit','volume_unit','pieces_unit').all()
the output is:
In [19]: Recipe.objects.select_related('mass_unit','volume_unit','pieces_unit').all()
Out[19]: SELECT "recipes_recipe"."id",
"recipes_recipe"."name",
"recipes_recipe"."slug",
"recipes_recipe"."primary_unit",
"recipes_recipe"."mass_unit_id",
"recipes_recipe"."mass_quantity",
"recipes_recipe"."volume_unit_id",
"recipes_recipe"."volume_quantity",
"recipes_recipe"."pieces_unit_id",
"recipes_recipe"."pieces_quantity",
"recipes_recipe"."updated",
"recipes_recipe"."timestamp",
"single_measurements_singlemeasurements"."id",
"single_measurements_singlemeasurements"."name",
"single_measurements_singlemeasurements"."slug",
"single_measurements_singlemeasurements"."formtype",
"single_measurements_singlemeasurements"."quantity",
"single_measurements_singlemeasurements"."updated",
"single_measurements_singlemeasurements"."timestamp",
T3."id",
T3."name",
T3."slug",
T3."formtype",
T3."quantity",
T3."updated",
T3."timestamp",
T4."id",
T4."name",
T4."slug",
T4."formtype",
T4."quantity",
T4."updated",
T4."timestamp"
FROM "recipes_recipe"
LEFT OUTER JOIN "single_measurements_singlemeasurements"
ON
Execution time: 0.001236s [Database: default]
And we can see the sql is incomplete, it has to show three left inner joins but it stops at ON.
Whereas if I try:
Recipe.objects.select_related('mass_unit').all()
It shows the full sql:
In [20]: Recipe.objects.select_related('mass_unit').all()
Out[20]: SELECT "recipes_recipe"."id",
"recipes_recipe"."name",
"recipes_recipe"."slug",
"recipes_recipe"."primary_unit",
"recipes_recipe"."mass_unit_id",
"recipes_recipe"."mass_quantity",
"recipes_recipe"."volume_unit_id",
"recipes_recipe"."volume_quantity",
"recipes_recipe"."pieces_unit_id",
"recipes_recipe"."pieces_quantity",
"recipes_recipe"."updated",
"recipes_recipe"."timestamp",
"single_measurements_singlemeasurements"."id",
"single_measurements_singlemeasurements"."name",
"single_measurements_singlemeasurements"."slug",
"single_measurements_singlemeasurements"."formtype",
"single_measurements_singlemeasurements"."quantity",
"single_measurements_singlemeasurements"."updated",
"single_measurements_singlemeasurements"."timestamp"
FROM "recipes_recipe"
LEFT OUTER JOIN "single_measurements_singlemeasurements"
ON ("recipes_recipe"."mass_unit_id" = "single_measurements_singlemeasurements"."id")
ORDER BY "recipes_recipe"."name" ASC
LIMIT 21
Here it does not stop at ON. It shows the full.
How to ensure --print-sql shows the full sql.
Add these to your settings.py:
for python manage.py shell_plus --print-sql:
SHELL_PLUS_PRINT_SQL_TRUNCATE = {truncate limit} (it defaults to 1000)
for python manage.py runserver_plus --print-sql:
RUNSERVER_PLUS_PRINT_SQL_TRUNCATE = {truncate limit} (it defaults to 1000)
Note the truncate limit is a number of characters, NOT lines, to truncate the sql output to.
Including
SHELL_PLUS_PRINT_SQL_TRUNCATE = None
in your settings.py file will ensure --print-sql shows the full SQL query.
You can read more about the configurations here
So I'm trying to populate a model in django using a postgres (postgis) database. The problem I'm having is inputting the datetimefield. I have written a population script but every time I run it I get the error django.db.utils.IntegrityError: null value in column "pub_date" violates not-null constraint. The code below shows my model and the part of the population script that applies to the table.
The model:
class Article(models.Model):
authors = models.ManyToManyField(Author)
location = models.ForeignKey(Location)
article_title = models.CharField(max_length=200, unique_for_date="pub_date")
pub_date = models.DateTimeField('date published')
article_keywords = ArrayField(ArrayField(models.CharField(max_length=20, blank=True), size=8), size=8,)
title_id = models.CharField(max_length=200)
section_id = models.CharField(max_length=200)
And the population script:
def populate():
add_article(
id = "1",
article_title = "Obama scrambles to get sceptics in Congress to support Iran nuclear deal",
pub_date = "2015-04-06T20:38:59Z",
article_keywords = "{obama, iran, debate, congress, america, un, republican, democrat, nuclear, isreal}",
title_id = "white-house-scrambles-sceptics-congress-iran-nuclear-deal",
section_id = "us-news",
location_id = "1"
)
def add_article(id, article_title, pub_date, article_keywords, title_id, section_id, location_id):
article = Article.objects.get_or_create(article_title=article_title)[0]
article.id
article.article_title
article.pub_date
article.article_keywords
article.title_id
article.section_id
article.location_id
article.save()
return article
if __name__ == '__main__':
print "Starting Newsmap population script..."
populate()
I've searched around for ages but there seems to be no solution to this specific problem. Any help much appreciated!!
The issue is that you do not pass to Article.objects.get_or_create the data needed to create a new object in case none already exists.
What you need to do is (see the documentation for get_or_create):
article = Article.objects.get_or_create(
article_title=article_title,
pub_date=pub_date,
defaults={
'id': id,
'article_keywords': article_keywords,
# etc...
}
)[0]
The data passed using the defaults argument will only be used to create a new object. The data passed using other keyword arguments will be used to check if an existing object matches in the database.
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)
First post to stackoverflow I did do a search and came up dry. I also own
the django book (Forcier,Bissex,Chun) and they don't explain how to do
this. In short I can't figure out how to progmatically add a data via
a python shell script to the ManyToMay model..
from django.db import models
from django.contrib import admin
class Client(models.Model):
client = models.CharField(max_length=256, primary_key=True)
access = models.DateField()
description = models.TextField()
host = models.CharField(max_length=256)
lineEnd = models.CharField(max_length=256)
options = models.TextField()
owner = models.CharField(max_length=100)
root = models.CharField(max_length=256)
submitOptions = models.CharField(max_length=256)
update = models.DateField()
def __unicode__(self):
return str(self.client)
admin.site.register(Client)
class Change(models.Model):
"""This simply expands out 'p4 describe' """
change = models.IntegerField(primary_key=True)
client = models.ManyToManyField(Client)
desc = models.TextField()
status = models.CharField(max_length=128)
def __unicode__(self):
return str(self.change)
admin.site.register(Change)
Here is what I have which works but I don't know how to add the
ManyToMany. I can't seem to figure out how to progmatically call it.
I know the row in SQL exists.
--- massImport.py ---
# Assume the client "clientspec" exists. I know how to create that if
neeeded.
changes = [ { 'change': 123, 'desc': "foobar", status': "foobar",
client': "clientspec", }]
for item in changes:
entry = Change(
change = item['change'],
desc = item['desc'],
status = item['status'],
# client = Client.objects.filter(client=item['client'])
)
entry.save()
Can anyone show me where the error of my ways is. I would really
appreciate it.
Thanks!!
Turns out Tiago was very close..
# Assume the client "clientspec" exists. I know how to create that if
neeeded.
changes = [ { 'change': 123, 'desc': "foobar", status': "foobar",
client': "clientspec", }]
for item in changes:
entry = Change()
entry.change = item['change']
entry.desc = item['desc']
entry.status = item['status']
entry.time = datetime.datetime.fromtimestamp(float(item['time']))
entry.client.add(Client.objects.get(client=item['client']))
entry.save()
So.. I will give props to Tiago
.filter returns a list, when you need is a single object, so you should use .get(client=item['client'])
I tried the code but i got error
ValueError: "<Change: 123 -- foobar>" needs to have a value for field "change" before this many-to-many relationship can be used
Manytomany(entry.client.add) can be used only after saving the field ie entry.save()
There may be a lot of clients so you can use:
changes = [{'change': 123, 'desc': "foobar", 'status': "foobar",
'client': ("client1","client2"),},{......]
for item in changes:
entry = Change(
change = item['change'],
desc = item['desc'],
status = item['status'],)
entry.save()
for c in item['client']:
entry.client.add(Client.objects.get(client=c))