django orm join without foiriegn key - orm

Setup
Django 2.0.2
MariaDB 10.2
Windows Server 2012
models.py
class Postreply(models.Model):
replyuid = models.BigAutoField(db_column='ReplyUID', primary_key=True)
postuid = models.BigIntegerField(db_column='PostUID')
useruid = models.BigIntegerField(db_column='UserUID')
content = models.TextField(db_column='Content')
registerdate = models.DateTimeField(
db_column='RegisterDate', default=datetime.datetime.today().strftime("%Y-%m-%dT%H:%M:%S"))
class Meta:
managed = False
db_table = 'postreply'
class Postinfo(models.Model):
postuid = models.BigAutoField(db_column='PostUID', primary_key=True)
useruid = models.BigIntegerField(db_column='UserUID')
content = models.TextField(db_column='Content')
replycount = models.IntegerField(db_column='ReplyCount', default=0)
registerdate = models.DateTimeField(
db_column='RegisterDate', default=datetime.datetime.today().strftime("%Y-%m-%dT%H:%M:%S"))
class Meta:
managed = False
db_table = 'postinfo'
class Userinfo(models.Model):
useruid = models.BigAutoField(db_column='UserUID', primary_key=True)
useremail = models.CharField(
db_column='UserEmail', unique=True, max_length=100)
userpassword = models.CharField(db_column='UserPassword', max_length=128)
passwordsalt = models.CharField(db_column='PasswordSalt', max_length=128)
usersex = models.IntegerField(db_column='UserSex')
userage = models.IntegerField(db_column='UserAge')
username = models.CharField(
db_column='UserName', max_length=100, default=0)
class Meta:
managed = False
db_table = 'userinfo'
I want filter the postreply table by the postuid field to
and get userinfo instance by useruid in fitered postreply
if postinfo ex)
postuid =3
postreply ex)
postuid = 3 useruid =21 replyuid= 1
postuid = 3 useruid =22 replyuid= 2
postuid = 3 useruid =21 replyuid= 3
postuid = 2 useruid =21 replyuid= 4
postuid = 3 useruid =33 replyuid= 5
userinfo ex)
useruid = 21 username = 'A'
useruid = 22 username = 'B'
useruid = 33 username = 'C'
if put postuid = 3 i want this
postuid = 3 useruid =21 replyuid= 1 username = 'A'
postuid = 3 useruid =22 replyuid= 2 username = 'B'
postuid = 3 useruid =21 replyuid= 3 username = 'A'
postuid = 3 useruid =33 replyuid= 5 username = 'C'
how to this

By using the values_list method you extract a list of just the relevant user ids and then use that to filter the Userinfos based on that list, like so:
chosen_id = 3
user_ids = Postreply.objects.filter(postuid=chosen_id).values_list('useruid')
users = Userinfo.objects.filter(userid__in=user_ids)

Related

Field not exist issue

I am using the Odoo 12 Community version. When I navigate to an employee an error shows ValueError: Field 'ifsc' does not exist and can't open the employee menu. I have inherited employee and it exists in both view and model.
class HrEmployeeInherit(models.Model):
_inherit = 'hr.employee'
sno = fields.Integer(string='Serial No.')
pay = fields.Integer(string='Paycode')
employee_name = fields.Char(string='Emp Name')
designation = fields.Char(string="Designation")
account = fields.Char(string="Account")
bank = fields.Char(string="Bank")
doj = fields.Date(string="Date Of Joining")
ifsc = fields.Char(string="IFSC Code")
present = fields.Float(string="Present Day")
m = fields.Char(string="M-L")
wd = fields.Float(string="WD")
sat = fields.Integer(string="Saturday/Holiday")
week = fields.Integer(string="WeekOff")
leave = fields.Float(string="Leave Adjustment")
payable = fields.Float(string="Total Payable Days")
ot = fields.Float(string="Tdays-OT")
days = fields.Integer(string="T.Days")
wages = fields.Integer(string="Basic wages")
curre = fields.Float(string="Current sal")
sal = fields.Integer(string="% of Salary")
covid = fields.Float(string="Covid 19 salary")
pf = fields.Float(string="PF")
esi = fields.Float(string="Esi")
pay = fields.Integer(string="Payable")
adv = fields.Integer(string="Advance")
tds = fields.Integer(string="Tds")
netpay = fields.Float(string="Net Payable")
icici = fields.Float(string="ICICI")
I have added 'depends': ['base','hr_contract','hr','hr_payroll'] in depends.

SQL Server CASE clause on where inside parenthesis

I have this problem in my SQL code:
I will only show my WHERE clause, because it is a bit long,
this is it:
where
((#account_status = 1027 AND a.AccountStatus = 1027 AND a.FolioNo =
#folio_no AND b.ReservationNo = #reservation_id)) OR
((#account_status = 1026 AND a.AccountStatus = 1026 AND a.FolioNo =
#folio_no AND b.ReservationNo = #reservation_id)) OR
((#account_status = 1025 AND a.AccountStatus = 1025 AND #trans_code = 1 AND
a.AccountStatementTransCode = 1 AND b.FolioNo = #folio_no AND
b.ReservationNo = #reservation_id)) OR
((#account_status = 1025 AND a.AccountStatus = 1025 AND #trans_code != 1
AND a.AccountStatementTransCode != 1 AND b.FolioNo = #folio_no AND
b.ReservationNo = #reservation_id)) OR
((a.FolioNo = #folio_no AND b.ReservationNo = #reservation_id AND
#trans_code = 2 AND a.AccountStatementTransCode = 2 AND
case
when #sub_category = 14 then i.category_id is null
else i.category_id = #sub_category
end )) OR
((a.FolioNo = #folio_no AND b.ReservationNo = #reservation_id AND
#trans_code = 3 AND a.AccountStatementTransCode = 3 AND i.category_id =
#sub_category)) OR
((a.FolioNo = #folio_no AND b.ReservationNo = #reservation_id AND
#trans_code = 4 AND a.AccountStatementTransCode = 4 AND i.category_id =
#sub_category)) OR
((a.FolioNo = #folio_no AND b.ReservationNo = #reservation_id AND
#trans_code = 5 AND a.AccountStatementTransCode = 5 AND i.category_id =
#sub_category)) OR
((a.FolioNo = #folio_no AND b.ReservationNo = #reservation_id AND
#trans_code = 6 AND a.AccountStatementTransCode = 6 AND i.category_id =
#sub_category))
I want that if input is #sub_category = 14 then it will return the category with NULL values, else it will return the #sub_category values.
How can I do that ?
Replace CASE expression logic with below
AND
1 = CASE WHEN #sub_category = 14 AND i.category_id is null
THEN 1
WHEN #sub_category <> 14 AND i.category_id = #sub_category
THEN 1
ELSE 0
END
Change your CASE to:
case
when #sub_category = 14 then null
else i.category_id = #sub_category
end
TRY THIS: Simple way, If your category_id never hold -1 or you can use the value that will never be in category_id i.e. 0,-1
AND ISNULL(i.category_id, -1) = CASE WHEN #sub_category = 14 THEN
-1
ELSE #sub_category END

Linq query with GROUP BY on multiple fields, SUM and COUNT

I'm trying to use a LINQ SQL to query my database.
Let's say I have some data that looks like this:
var1 var2 var3 qty
1 a 1a 50
1 a 1a 25
2 b 2b 10
2 b 2b 15
2 b 2b 10
3 a 3a 25
I know how to format my query in SQL. It would be something like this:
SELECT var1, var2, var3, count(*) AS count, sum(qty) As quantity
FROM MyTable
GROUP BY var1, var2, var3
In this case the output would be something like this:
var1 var2 var3 Count Qty
1 a 1a 2 75
2 b 2b 3 35
3 a 3a 1 25
How can I do the same thing with LINQ in vb.net
Dim groups = From j In MyTable
Group By j.var1, j.var2, j.var3 Into g
Select new {var1 = g.var1,
var2 = g.var2,
var3 = g.var3,
quantity = sum(g.qty),
count = count(*)}
That's not quite right, but I think it's close. I don't understand the syntax of the group by in VB.NET.
You want to group by an anonymous type, this is the syntax in VB.NET (note the Key):
Dim groups =
From j In MyTable
Group By x = New With {Key .var1 = j.var1, Key .var2 = j.var2, Key .var3 = j.var3} Into g = Group
Select New With {
.var1 = x.var1,
.var2 = x.var2,
.var3 = x.var3,
.quantity = g.Sum(Function(r) r.qty),
.count = g.Count()
}
You will have to use anonymous type like this:-
Group j By Key = New With { Key .Var1 = j.var1,
Key .Var2 = j.var2,
Key .Var3 = j.var3 } Into Group
Select New With { .var1 = Key.Var1,
.var2 = Key.Var2,
.var3 = Key.Var3,
.quantity = Group.Sum(Function(x) x.qty),
.count = Group.Count()
}

SQL: Variable to update a set of items

SO, each item has an id, a setId, and a name.
Current data may only have one NAME field filled out in an entire set.
EX>
>ID = 1 >NAME = 'Bob' >SETID = 5
>ID = 2 >NAME = NULL >SETID = 5
>ID = 3 >NAME = NULL >SETID = 5
>ID = 4 >NAME = NULL >SETID = 5
I am looking for an SQL script that GET the one record that is not null in a "SET"
SET the remaining items in the "SET" for that "NAME" record.
The end result I am aiming for would look like this:
>ID = 1 >NAME = 'Bob' >SETID = 5
>ID = 2 >NAME = 'Bob' >SETID = 5
>ID = 3 >NAME = 'Bob' >SETID = 5
>ID = 4 >NAME = 'Bob' >SETID = 5
Assuming there is only one Name in a set that is not null, you could use a CTE and do something like:
;WITH NameHelper AS
(
SELECT
Name,
SetID
FROM MyTable
WHERE Name IS NOT NULL
GROUP BY Name, SetID
)
UPDATE MyTable SET Name = NameHelper.Name
FROM MyTable
INNER JOIN NameHelper ON MyTable.SetID = NameHelper.SetID

Error in assigning object of nullable type in vb.net

I am new to VB.net and facing a strange situation. I have a structure that contains another structure. The inner structure is nullable. Now wht I do is something like the following. I create a new instance of the inner structure, set the member variables and assign the whole structure to the inner structure of the parent. But it is giving an error. The assignment is not successful. If I try to peek into the structure in the watch window, it says "property evaluation failed" for the HasValue and Value properties.
Dim testData As List(Of TestData) = Nothing
Dim testData_List1 As New TestData
With testData_List1.commonTestParam
.AccuchekActiveEnergy = 2.56
.AccuchekActiveEnergyUnit = ActiveEnergyUnit.KiloWattHour
.AccuchekApparentEnergy = 34.56
.AccuchekApparentEnergyUnit = ApparentEnergyUnit.VoltAmpereHour
.AccuchekFrequency = 1
.AccuchekRange = "20474 ewr 34324"
.AccuchekType = AccuchekType.AccuchekOne
.ActiveLoadRPhase = 145
.AvgActiveLoad = 2.56
.AvgActiveLoadUnit = ActiveLoadUnit.Watt
.AvgPowerFactor = 0
.AvgPowerFactorType = PowerFactorType.PFLag
.ConditionalFlag1 = 0
.ConsumerNo = "343122050242"
.CurrentRPhase = 1
.GeneralFlag1 = 0
.InstantaneousPFRPhase = 2
.ManufacturingYear = 2009
.MeterActiveEnergy = 258.89
.MeterActiveEnergyUnit = ActiveEnergyUnit.KiloWattHour
.MeterActiveError = 20
.MeterApparentError = 14
.MeterConstant = 3200
.MeterConstantUnit = MeterConstantUnit.RevsPerkVAh
.MeterMake = "DS"
.MeterSNo = "6563402"
.MeterTypeAndClass = MeterTypeAndClass.MTCElectorMechWith20
.MTFID = "123456789"
.NoofTestRevolutions = 100
.PulseCriteria = 0
.RatedBasic = 25
.RatedMax = 30
.RatedVoltage = 15
.ReactiveCurrentRPhase = 145
.RemarkID = 0
.TestDateAndTime = "100320101545"
.TestDuration = 2145
.TesterCode = 0
.TestID = "147852"
.TestMode = TestMode.TMOpticalScanner
.TestNumber = 0
.VoltageRPhase = 145
End With
Dim accuchek3TestParameters1 As New Accuchek3PhaseTestParameters
With accuchek3TestParameters1
.AccuchekReactiveLagEnergy = 2.46
.AccuchekReactiveLagEnergyUnit = ReactiveEnergyUnit.KiloVoltAmpereReactiveHour
.AccuchekReactiveLeadEnergy = 2.56
.AccuchekReactiveLeadEnergyUnit = ReactiveEnergyUnit.KiloVoltAmpereReactiveHour
.ActiveLoadBPhase = 14
.ActiveLoadYPhase = 15
.AvgApparentLoad = 10
.AvgApparentLoadUnit = ApparentLoadUnit.KiloVoltAmpere
.AvgReactiveLagLoad = 14
.AvgReactiveLagLoadUnit = ReactiveLoadUnit.KiloVoltAmpereReactive
.AvgReactiveLeadLoad = 15
.AvgReactiveLeadLoadUnit = ReactiveLoadUnit.KiloVoltAmpereReactive
.ConditionalFlag2 = 0
.ConditionalFlag3 = 0
.CTRatio = 1.23
.CurrentBPhase = 10
.CurrentYPhase = 11
.InstantaneousPFBPhase = 0
.InstantaneousPFYPhase = 1
.MeterApparentEnergy = 1.01
.MeterApparentUnit = ApparentEnergyUnit.KiloVoltAmpereHour
.MeterReactiveLagEnergy = 1.25
.MeterReactiveLagError = 1.25
.MeterReactiveLagUnit = ReactiveEnergyUnit.KiloVoltAmpereReactiveHour
.MeterReactiveLeadEnergy = 1.45
.MeterReactiveLeadError = 1.56
.MeterReactiveLeadUnit = ReactiveEnergyUnit.KiloVoltAmpereReactiveHour
.PercentageLoad = 1
.PTRatio = 1
.ReactiveCurrentBPhase = 10
.ReactiveCurrentYPhase = 11
.VoltageBPhase = 10
.VoltageYPhase = 10
End With
testData_List1.accuchek3TestParameters = accuchek3TestParameters1
testData.Add(testData_List1)
Can somebody please guide me?
Your first line is:
Dim testData As List(Of TestData) = Nothing
Then at the bottom you do
testData.Add(testData_List1)
I can't see anywhere in between where you do something like:
testData = New List(Of TestData)()
Though it's slightly hard to read since you've got both a variables and types with TestData as their name (or part of their name) so I might just be missing that.