count the sales of a worker - python

I am trying to count the sales made by a worker but I get the following error when using the code mentioned below:
TypeError: object of type 'bool' has no len()
class Movement_type (models.Model):
_name = 'project_rc.movement_type'
_rec_name = 'movement_type'
type_movement = fields.Selection ([('purchase', 'Purchase'), ('sale', 'Sale'), ('merma', 'Merma')], string = "Movement type", required = True)
class Worker (models.Model):
_name = 'project_rc.worker'
_rec_name = 'name'
sales_counter = fields.Integer (string = "Sales made", compute = "get_sales_realized", store = True)
#api.depends('move_type_ids')
def get_sales_realized (self):
for rec in self:
rec.count_sale = len (rec.move_type_ids.mov_type == 'sale')

I'm not familiar with whatever framework you are using, but if you look at the error you are getting you can see that it is correct.
On line 3, you write rec.move_type_ids.mov_type == 'sale'. It doesn't matter what rec.move_type_ids.mov_type is, when you compare it to something with ==, the answer will either be True or False. It doesn't make sense to take the length of a boolean (t/f).
From the context, I'm guessing that rec.move_type_ids is a list of objects and you want to figure out how many of them have a mov_type property equal to 'sale'. If that's the case, then you could easily do that with a for loop:
sales = []
for thing in rec.move_type_ids:
if thing.type == 'sale':
sales.append(thing)
rec.count_sale = len(sales)
If you want to get a little fancier, you can do that with a filter function:
rec.count_sale = len(filter(lambda x: x.mov_type == 'sale', rec.move_type_ids))

Related

How to get integer ID of Django Factory Boy object?

I have a factory boy factory that uses Django that I need to access the ID of the generated objects. However, whenever I attempt to get that ID, I receive TypeErrors. Any idea what I am missing?
# factories.py
class PartNoFactory(factory.django.DjangoModelFactory):
class Meta:
model = PartNo
id = factory.fuzzy.FuzzyInteger(1, 1000000, step=1)
# have also tried id = factory.Sequence(lambda n: n + 1)
# have also tried id = int(factory.Sequence(lambda n: n + 1)), which results in error "type Sequence cannot be assigned to paramater "_x"
# test_factories.py
def mock_child_part_nos(arg_1: PartNo) -> 'list[int]':
mock_part_no_one = PartNoFactory()
mock_part_no_two = PartNoFactory()
mock_part_no_three = PartNoFactory()
return [mock_part_no_one.id, mock_part_no_two.id, mock_part_no_three.id]
# if using FuzzyInteger: "Expression of type "list[FuzzyInteger]" cannot be assigned to return type "list[int]"
# if using Sequence: "Expression of type "list[Sequence]" cannot be assigned to return type "list[int]"

List Manipulation Based on Class Variables

Apologies if I explain something wrong or use the wrong wording, my programmer vocabulary isn't the best. If anyone understands my problem and has better ways of explaining it feel free to do so. I have a problem similar to a problem here. I want to remove items from a list that occur in another list. But one list will have strings that reference the variable "name" within class objects.
class sword:
name = 'swordName'
class bow:
name = 'bowName'
class axe:
name = 'axeName'
inventory = [sword, bow, sword, axe]
select = ['bowName', 'swordName']
I want to be able to create a list "selectedItems" with the class objects out of inventory based off of the strings in "select" that are equal to the "name" of the class objects. It also needs to work if "inventory" and "select" both have duplicates in them.
Output:
>> inventory = [bow, axe]
>> selectedItems = [bow, sword]
One other thing I would like the program to ignore if there are more "name"s in select than there are corresponding class objects in "inventory", and to ignore if a string in "select" has no corresponding class objects.
For example, if "inventory" is [sword, axe] and "select" is ['bowName', 'non-existent', 'axeName'], the result is that "inventory" is [sword] and "selectedItems" is [axe].
A simple way of explaining this is that select will take from inventory, but if select can't take from inventory nothing happens.
You may make base class with magic methods __eq__ and __hash__ which can allow you to manage comparing your objects as you want:
class BaseItem:
name = None
def __init__(self):
self.__name = self.name
def __eq__(self, other):
return self.__name == other
def __hash__(self):
return id(self.__name)
def __repr__(self):
return f"'{self.__name}'"
class Sword(BaseItem):
name = "swordName"
class Bow(BaseItem):
name = "bowName"
class Axe(BaseItem):
name = "axeName"
inventory = [Sword(), Bow()]
select = ["swordName", "bowName", "axeName", "swordName", "bowName"]
# casting lists into sets and getting difference between them
result = set(inventory) - set(select)
print(result) # output {'swordName', 'bowName'}
eq - actually is unused here but i added that you can compare your objects with strings, lists etc:
Sword() in ["swordName"] # true
Sword() in ["bowName"] # false
Sword() == "swordName" # true
Sword() == "bowName" # false
hash - need to comparing two objects, actually it use for getting difference between two sets
repr - it is not really required method, it needs just for pretty displaying of objects
selectedItems = list()
# make a new list of the names of the objects in the inventory
# inventory and inventory names have the same index for the same item
inventory_names = [x.name for x in inventory]
for s in select:
if s in inventory_names:
index = inventory_names.index(s)
inventory_names.pop(index)
selectedItems.append(inventory.pop(index))

python object attribute randomly deleting itself

i have a problem with python objects where i am creating and iterating over many objects simultaneously.
objects are always created with the correct attributes, but when i iterate over those objects, i check for a certain attribute in the object, this specific attribute randomly gets deleted from the object and then i get an error that the object does not have this attribute.
code:
dead_list = []
for key, trackable_vehicle in self.lane_vehciles.items():
if trackable_vehicle.vehicle_status == 'DEAD' :
dead_list.append(key)
for key in dead_list:
save_object(trackable_vehicle.vehicle_type+'_'+str(trackable_vehicle.object_ID), trackable_vehicle)
self.lane_vehciles.pop(key, None)
Error: 'TrackableTruck' object has no attribute 'vehicle_status'
please note that this code works for me 95% of the time, and this happens for random objects although all objects has the same structure.
after a lot of debugging i just cant get my head around why this happens. the object is correctly created and if i print it before iteration it does have the "vehicle_status" attribute but after iteration the attribute disappears from the object
for example:
object at creation:
{"object_ID": 55, "vehicle_type": "truck", "OTS": "2020-03-10 16:07:16", "lane_ID": 2.0, "vehicle_status": "ALIVE"}
object after iteration:
{"object_ID": 55, "vehicle_type": "truck", "OTS": "2020-03-10 16:07:16", "lane_ID": 2.0}
i hope someone with better knowledge at python than myself can help me.
thanks
EDIT object definition:
class TrackableTruck:
def __init__(self, object_ID, vehicle_type, OTS, lane_ID, vehicle_status):
# info from tracking server
self.object_ID = object_ID
self.vehicle_type = vehicle_type
self.OTS = OTS
self.lane_ID = lane_ID
self.vehicle_status = vehicle_status
code to check and change vehicle status:
d = pickle.loads(full_msg[self.HEADERSIZE:])
d = json.loads(d)
vehicle_type = str(d['vehicle_type'])
vehicle_lane = int(d['lane_ID'])
vehicle_id = int(d['object_ID'])
vehicle_status = d['vehicle_status']
if vehicle_lane == 1:
trackable_vehicle = self.streetLane_1.get_vehicle(vehicle_id)
if trackable_vehicle is None:
self.streetLane_1.add_vehicle(d)
else:
trackable_vehicle.vehicle_status = 'DEAD'
object creation code:
def object_decoder(self,json_obj):
return TrackableTruck(int(json_obj['object_ID']), json_obj['vehicle_type'], json_obj['OTS'], json_obj['lane_ID'], json_obj['vehicle_status'])
def add_vehicle(self, json_obj):
trackable_vehicle = self.object_decoder(json_obj)
self.lane_vehciles[int(trackable_vehicle.object_ID)] = trackable_vehicle

python check if str is in a list of objects

I have a class. In short, to initialize you have to provide it with some values when you create it:
class Silo:
def __init__(self, id, name, netid, node):
self.id = id
self.name = name
self.node = node
self.netid = netid
I may have more than one Silo and they are dynamically created by way of an sqllite database. For clarity's sake I've forgone the code for the database queries and instead printed the list of silos below in my example:
global siloList # siloList is a list of the Silos objects.
siloList = {} # Initialize
print(silos) # return: [(1, 'Silo 1', 1, 1), (2, 'Silo 2', 1, 4)]
for silo in silos: # loop through silos for each silo
newSilo = Silo(silo[0], silo[1], silo[2], silo[3]) # Create the object from Silo class
siloList[silo[0]] = newSilo # Create a list for each Silo object with the ID as the index
I would like to retrieve the ID for each object based on the name I enter so that I can do things with that class.
For example:
userInput = "Silo 2"
# Obtain "2" based on input "Silo 2" somehow
siloList[2].netid = 9 # Change the netid with siloList[id]
I can't figure out how to obtain the id of that object from a name appearing in it, though.
I found a silo = next((x for x, obj in enumerate(siloList) if obj['name'] == userInput), None) but this gives me an error TypeError: 'int' object is not subscriptable and I can't quite figure out how to make it work for my needs (or even if it will work or whatelse would be better).
Thanks.
You can get a list of the matching Silo's IDs with
matching_silo_ID_list = list(id_ for id_ in siloList if siloList[id_].name == userInput)
If you are sure that the matching list has exactly one element you can then safely use
matching_ID = matching_silo_ID_list[0]
to do
siloList[matching_ID].netid = 9
NB. I guess your siloList = {} is actually a dictionary.

Convert Data Objects to Strings for Script

I am getting this error each time I try to run this app in its present state.
TypeError: cannot concatenate 'str' and 'GameData' objects
I am trying to get a data object from my Game(GameData) class onto the browser with my html. It's a subclass of GameData() which is a template class.
class GameData(object): #This class is the template for the data for each game.
def __init__(self):
self.title = ''
self.genre = ''
self.description = ''
self.developer = ''
self.rating = ''
self.image = ''
class Game(GameData): #Thas class holds all the data for each game.
def __init__(self):
#object for Castlevania
self.castlevania = GameData()
self.castlevania.title = 'Castlevania'
self.castlevania.genre = 'Action Platformer'
self.castlevania.description = 'Released in 1986 in Japan, Castlevania for the NES and Famicom Disc System spawned a series rich in action as well as exploration. This first game was merely a simple platformer but it inspired many changes to the formula over the years and invented the "Metroidvania" genre.'
self.castlevania.developer = 'Konami'
self.castlevania.rating = '7.5/10'
self.castlevania.image = 'images/t_castlevania.png'
There are other objects but if I can get one of them to work I can figure out the rest. I need it to get into this elif statement highlighted with a comment.
class MainHandler(webapp2.RequestHandler):
def get(self):
i = Intro()
d = GameData()
g = Game()
if self.request.GET:
page = self.request.GET['page']
if page == 'main_page':
self.response.write(i.head + i.main_page + i.main_title + i.main_links)
elif page == 'castlevania': #The data needs to go in this concatenation.
self.response.write(i.head + i.main_page + i.castlevania + (the data object should go here) + i.main_links)
From there I know what to do. I just need to know how to convert the data into a string so I can concatenate it. If anyone can help I would appreciate it. Also I tried using an array for the objects but that didn't work for me either.
You just need to include the __str__ function in your Game(GameData) class.
eg.
def __str__(self):
# Here you would put whatever logic in terms of returning a string
# representation of your game object. Eg:
return self.castlevania.title
Then, you would simply call str(g) where g is your Game(GameData) object

Categories

Resources