Given below is my Model definition and I have added this module part of the Admin. I'm trying to create new row and while selecting value '3' or any other value for Duration field(listed as select fields), I get the following error.- "Value 3 is not a valid choice".
Please provide your inputs.
Model Definition
NO_OF_HRS = (
('1','One'),
('2','Two'),
('3','Three'),
('4','Four'),
('5','Five'),
('6','Six'),
('7','Seven'),
('8','Eight'),
('9','Nine'),
('10','Ten'),
('11','Eleven'),
('12','Twelve'),
)
YR_MONTH = (
("Y", "Year"),
("M", "Month"),
)
POS_STATUS = (
("A", "Active"),
("C", "Closed"),
)
datecreated = models.DateTimeField()
volposition = models.CharField(max_length=300)
roledesc = models.CharField(max_length=5000)
noofhours = models.IntegerField(blank = True,null = True)
Qualreqt = models.CharField(max_length=8000)
Duration = models.IntegerField(choices=NO_OF_HRS,blank = True,null = True)
Durationyrmon = models.CharField(choices=YR_MONTH,max_length=10)
posstatus = models.CharField(choices=POS_STATUS,max_length=1)
teamrelation = models.CharField(max_length=50)
When you use choices, the first value of the tuple is the value that will be stored in the database and the second value is the value that will be shown in the admin.
In NO_OF_HRS the values are strings (for example '1', '2') but it is a models.IntegerField so the values should be integers. That's why you're now getting an error.
Opened a ticket on django with fix and dirty fix:
https://code.djangoproject.com/ticket/24897
Related
I have a table called Apparatus and there is a column there called "quantity",
I have another table called Transaction where you can select the apparatus id and reserve a quantity
how can i minus the quantity in the transaction from the quantity in apparatus? I'm getting undefined index: id error...
here is a code in my controller:
if (isset($_POST['Transaction']))
{
$transaction->attributes = $_POST['Transaction'];
$transaction->save();
$apparatus = Apparatus::model()->findByPk($_POST['id']);
$apparatus->quantity = $apparatus->quantity - ($_POST['quantity']);
$apparatus->save();
Before doing arithematic operation, check whether the index id is present.
I am sure, your $_POST variables does not hold id as index.
So, i suggest to do the following:
if(Yii::app()->request->getPost('id') && Yii::app()->request->getPost('quantity') && Yii::app()->request->getPost('Transaction')){
$id = (int) Yii::app()->request->getPost('id');
$quantity = (int) Yii::app()->request->getPost('quantity');
$apparatus = Apparatus::model()->findByPk($id);
if($apparatus){
$apparatus->quantity = $apparatus->quantity - $quantity;
if($apparatus->validate()){
$apparatus->save();
}else{
// Log
var_dump($apparatus->errors);
}
}
}
Alternatively, you can dump {var_dump($_POST)} the post variables to see whether the $_POST contains id as index.
Here's what I did: (controller)
if (isset($_POST['Transaction']))
{
$transaction->attributes = $_POST['Transaction'];
$transaction->save();
$id=$transaction->apparatus_id=($transaction['apparatus_id']);
$quantity=$transaction->quantity=($transaction['quantity']);
$apparatus = Apparatus::model()->findByPk($id);
$apparatus->quantity = $apparatus->quantity - $quantity;
$apparatus->save();
}
I am trying to write a dapper query for IN clause, but it's not working throwing casting error saying "Conversion failed when converting the nvarchar value 'A8B08B50-2930-42DC-9DAA-776AC7810A0A' to data type int." . In below query fleetAsset is Guid converted into string.
public IQueryable<MarketTransaction> GetMarketTransactions(int fleetId, int userId, int rowCount)
{
//Original EF queries which I am trying to convert to Dapper
//var fleetAsset = (from logicalFleetNode in _context.LogicalFleetNodes
// where logicalFleetNode.LogicalFleetId == fleetId
// select logicalFleetNode.AssetID).ToList();
////This query fetches guid of assetprofiles for which user having permissions based on the assets user looking onto fleet
//var assetProfileIds = (from ap in _context.AssetProfileJoinAccounts
// where fleetAsset.Contains(ap.AssetProfile.AssetID) && ap.AccountId == userId
// select ap.AssetProfileId).ToList();
var fleetAsset = _context.Database.Connection.Query<string>("SELECT CONVERT(varchar(36),AssetID) from LogicalFleetNodes Where LogicalFleetId=#Fleetid",
new { fleetId }).AsEnumerable();
//This query fetches guid of assetprofiles for which user having permissions based on the assets user looking onto fleet
var sql = String.Format("SELECT TOP(#RowCount) AssetProfileId FROM [AssetProfileJoinAccounts] AS APJA WHERE ( EXISTS (SELECT " +
"1 AS [C1] FROM [dbo].[LogicalFleetNodes] AS LFN " +
"INNER JOIN [dbo].[AssetProfile] AS AP ON [LFN].[AssetID] = [AP].[AssetID]" +
" WHERE ([APJA].[AssetProfileId] = [AP].[ID]) " +
" AND ([APJA].[AccountId] = #AccountId AND LogicalFleetId IN #FleetId)))");
var assetProfileIds = _context.Database.Connection.Query<Guid>(sql, new { AccountId = userId, FleetId = fleetAsset, RowCount=rowCount });
Dapper performs expansion, so if the data types match, you should just need to do:
LogicalFleetId IN #FleetId
(note no parentheses)
Passing in a FleetId (typically via an anonymous type like in the question) that is an obvious array or list or similar.
If it isn't working when you remove the parentheses, then there are two questions to ask:
what is the column type of LocalFleetId?
what is the declared type of the local variable fleetAsset (that you are passing in as FleetId)?
Update: test case showing it working fine:
public void GuidIn_SO_24177902()
{
// invent and populate
Guid a = Guid.NewGuid(), b = Guid.NewGuid(),
c = Guid.NewGuid(), d = Guid.NewGuid();
connection.Execute("create table #foo (i int, g uniqueidentifier)");
connection.Execute("insert #foo(i,g) values(#i,#g)",
new[] { new { i = 1, g = a }, new { i = 2, g = b },
new { i = 3, g = c },new { i = 4, g = d }});
// check that rows 2&3 yield guids b&c
var guids = connection.Query<Guid>("select g from #foo where i in (2,3)")
.ToArray();
guids.Length.Equals(2);
guids.Contains(a).Equals(false);
guids.Contains(b).Equals(true);
guids.Contains(c).Equals(true);
guids.Contains(d).Equals(false);
// in query on the guids
var rows = connection.Query(
"select * from #foo where g in #guids order by i", new { guids })
.Select(row => new { i = (int)row.i, g = (Guid)row.g }).ToArray();
rows.Length.Equals(2);
rows[0].i.Equals(2);
rows[0].g.Equals(b);
rows[1].i.Equals(3);
rows[1].g.Equals(c);
}
Here's the problem:
I have an array that has information about users. Each entry is separated by a blank field in the array.
For this example let's say the data fields are ID, first, last, phone, and email. However, if a user doesn't have a value for a particular field, then it is omitted entirely.
So here is what the array looks like
users[0] = 45049345
users[1] = Bob
users[2] = Smith
users[3] = 789-456-1230
users[4] = bob#gmail.com
users[5] =
users[6] = 63515987
users[7] = Joe
users[6] = Schmoe
users[8] = joe#gmail.com
users[9] =
I want to loop this array and store the data for each user in a database, however I have no clue how to verify that I am storing the right information in the place because there is no pattern in the array. Since Joe doesn't have a phone number, his email is would be stored as his phone number. This would result in ever subsequent entry to be off by 1 index.
Any ideas on how to go about this?
P.S. I am using node.js
EDIT: here is an example of the actual data
021870143-14
lastName
firstName
U
5/16/1988
11/6/2008
A
11/6/2008 6:0:2
NF
245
MAIN ST.
101
NEW YORK
NY
10002
11/4/2008
34
SD1
MUNC1J-036
MAG1-1
LEG77
SENT34
CONG5
CNTY
34-1
10/27/2008 19:59:53
NF
Here's pseudo code because I don't know javascript. I'm basing this off the fact that I think Javascript has dictionaries/associative arrays/hash tables etc.
new_user = {}
for i from 0 to arr.length
if arr[i] = null/Omitted field/nil/None/whatever
database.add_entry(new_user) // Add finished user table to database
new_user = {} // Start new dictionary
else
field = arr[i]
if field contains '#'
new_user.email = field
else if field contains '-'
new_user.phone_number = field
else if is_a_number(field)
new_user.id = field
else if new_user has first_name
new_user.last_name = field
else
new_user.first_name = field
Use tokenization ..
example:
users[0] = "45049345,Bob,Smith,789-456-1230,bob#gmail.com";
users[1] = "63515987,Joe,Schmoe,-,joe#gmail.com";
Process:
for (user in users)
{
for (detail in user)
{
document.write (detail + "<br>");
}
}
The model is like this(in SQLAlchemy):
Class Cell(Base):
__tablename__ = "cell"
id = Column(Integer)
name = Column(String)
Class Sample(Base):
__tablename__ = "cell"
id = Column(Integer)
factor_id = Column(Integer, ForeignKey("cell.id"))
cell = relationship(Cell, backref = 'sample', order_by = "Cell.id")
When I execute the query like this:
DBSession.query(Sample).filter(Sample.cell.name == "a_string")
It throws an exception like this:
File "build/bdist.linux-x86_64/egg/sqlalchemy/orm/attributes.py", line 139, in __getattr__
key)
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object has an attribute 'name'
It seems that the cell field in Sample class doesn't have a field called name. Then how can I query Cell.name in Sample class with cell field? Does anyone have ideas about this?
Thanks!
There are various ways to achieve that:
1. use join(...) - I would opt for this one in your case
qry = session.query(Sample).join(Cell).filter(Cell.name == "a_string")
>> SELECT sample.id AS sample_id, sample.factor_id AS sample_factor_id
>> FROM sample JOIN cell ON cell.id = sample.factor_id
>> WHERE cell.name = :name_1
2. use any/has(...) - this will use a sub-query
qry = session.query(Sample).filter(Sample.cell.has(Cell.name == "a_string"))
>> SELECT sample.id AS sample_id, sample.factor_id AS sample_factor_id
>> FROM sample
>> WHERE EXISTS (SELECT 1
>> FROM cell
>> WHERE cell.id = sample.factor_id AND cell.name = :name_1)
#HistoryMSBType => This is a variable which can contain any varchar.
Depending upon it's value, i need to have different type of where clause.
How can I achieve this ?
SELECT * FROM stageTable map
WHERE id = 1
CASE #HistoryMSBType
WHEN 'Utilization Other' THEN
AND map.ColumnID = 4
WHEN 'Cost Other' THEN
AND map.ColumnID = 6
ELSE
AND map.ColumnName = #HistoryMSBType
END
SELECT *
FROM stageTable map
WHERE id = 1
AND (
(#HistoryMSBType = 'Utilization Other' AND map.ColumnID = 4)
OR
(#HistoryMSBType = 'Cost Other' AND map.ColumnID = 6)
OR
(isnull(#HistoryMSBType,'') NOT IN ('Utilization Other','Cost Other')
AND map.ColumnName = #HistoryMSBType)
)
You need the ISNULL to make it match the CASE-ELSE exactly, but it won't matter if it can never be null.