Create Model for 4-D kind of array in Django - python

I have some logic constructed for my Database for a Django webapp but I am quite unable to convert it into Model form that can be used in Models.py :
User : U
Transaction-ID : T
Datetime : D
Transaction-ID Status-1 for a today : A[0]
Transaction-ID Status-2 for a today : A[1]
Transaction-ID Status-3 for a today : A[2]
For above a logic can be constructed with N users : U[N] where U[i] -> T[i][] transaction, and each transaction has 3 transactional attributes T[j] -> A[j][3]. How should I proceed with constructing a model for the given details. Also if possible how can I store date wise Model for the three A[k] statuses of Transaction and add them for a week wise and month wise average and proceed with making the db.
meaning :
A particular user could have done variable number of Transactions, and for each transaction there is a key provided used to get the status of that particular transaction. Like the power points earned, bonus points earned and fame points earned. For periodically updating the 3 points earned daily, weekly and monthly across all transactions done by that user and storing them in the Database for each and every user what should be done.
It would have been easier in C++ but since my project is based on SQLite that runs inbuilt with Django framework it's hard to understand how many models should be used and how to link them to implement this system. Any advice would be appreciated.
4-D perspective is because of : entry = U[N][M][3][D]

I put some part of my project for this purpose and apologize for not summarizing the code in this answer (because I think summarizing it maybe would have mistakes without test so I decided used copy-paste a tested code).
When I want to read four nested Django admin model (4D) and use them in the code, I did the following procedures:
models.py:
from __future__ import unicode_literals
from django.db import models
from django.db.models.deletion import CASCADE
MODBUS_TYPES = (('tcp', 'Tcp'), ('udp', 'Udp'), ('ascii', 'Ascii'), ('rtu', 'Rtu'))
class BatteryMonitoringServer(models.Model):
enable = models.BooleanField(default=True)
name = models.CharField(max_length=150)
server_ip = models.GenericIPAddressField(default='0.0.0.0', null=True)
def __str__(self):
return self.name
class BatteryMonitoringDevice(models.Model):
bm_id = models.ForeignKey(BatteryMonitoringServer, on_delete=CASCADE)
enable = models.BooleanField(default=True)
name = models.CharField(max_length=100, null=True)
method = models.CharField(max_length=5, choices=MODBUS_TYPES)
bm_device_ip = models.GenericIPAddressField(default='127.0.0.1', null=True)
bm_device_port = models.IntegerField(default=5558, null=True)
baud_rate = models.IntegerField(null=True, default=9600)
class BatteryMonitoringSubDevice(models.Model):
enable = models.BooleanField(default=True)
name = models.CharField(max_length=100)
unit = models.IntegerField(default=1)
sub_bm_count = models.IntegerField(default=4, null=True, blank=True, name='bm')
fk = models.ForeignKey(BatteryMonitoringDevice, on_delete=CASCADE)
class BatteryMonitoringMeta(models.Model):
key = models.CharField(max_length=100)
value = models.CharField(max_length=100)
module = models.ForeignKey(BatteryMonitoringSubDevice, on_delete=CASCADE)
conf_reader.py
from battery_monitoring.models import BatteryMonitoringServer
from delta_device.utility import DictEncoder
class BMSubDeviceConf(object):
def __init__(
self,
start,
name,
unit,
bm,
meta_data):
self._start = start
self._name = name
self._unit = unit
self._bm = bm
self._meta_data = meta_data
#property
def start(self):
return self._start
#property
def name(self):
return self._name
#property
def unit(self):
return self._unit
#property
def bm(self):
return self._bm
#property
def meta_data(self):
return self._meta_data
class BMDeviceConf(object):
def __init__(
self,
bm_id,
start,
name,
method,
bm_device_ip,
bm_device_port,
baud_rate,
sub_devices=None):
self._id = bm_id
self._start = start
self._name = name
self._method = method
self._bm_device_ip = bm_device_ip
self._bm_device_port = bm_device_port
self._baud_rate = baud_rate
self._sub_devices = sub_devices or []
def add_sub_device(self, sub_device):
self._sub_devices.append(sub_device)
def get_sub_devices(self):
return self._sub_devices
#property
def start(self):
return self._start
#property
def id(self):
return self._id
#property
def name(self):
return self._name
#property
def bm_device_ip(self):
return self._bm_device_ip
#property
def bm_device_port(self):
return self._bm_device_port
#property
def baud_rate(self):
return self._baud_rate
class BMConf(object):
def __init__(
self,
start,
name,
server_ip,
devices=None,
): # :( :| :) (: :p
self._start = 'ON' if start else 'OFF'
self._name = name
self._server_ip = server_ip
self._devices = devices or []
def add_device(self, device):
self._devices.append(device)
def get_devices(self):
return self._devices
#property
def start(self):
return self._start
#property
def name(self):
return self._name
#property
def server_ip(self):
return self._server_ip
def get_server():
"""Using list method to make a fast sql reading."""
return list(BatteryMonitoringServer.objects.all())
def get_devices(dev):
return list(dev.batterymonitoringdevice_set.all())
def get_sub_devices(sub_dev):
return list(sub_dev.batterymonitoringsubdevice_set.all())
def get_metadata(metric):
return list(metric.batterymonitoringmeta_set.all())
class BMReadConf(object):
"""BM configuration Reader"""
def __init__(self):
pass
#classmethod
def get_bm_config(cls):
"""Read BM metrics and return it on a object list"""
result = list()
for srv in get_server():
data = BMConf(srv.enable,
srv.name,
srv.server_ip,)
for dev in get_devices(srv):
device = BMDeviceConf(
dev.bm_id,
dev.enable,
dev.name,
dev.method,
dev.bm_device_ip,
dev.bm_device_port,
dev.baud_rate,
)
for sub_dev in get_sub_devices(dev):
meta_data = {}
for meta in get_metadata(sub_dev):
meta_data[meta.key] = meta.value
sub_device = BMSubDeviceConf(
sub_dev.enable,
sub_dev.name,
sub_dev.unit,
sub_dev.bm,
meta_data,
)
device.add_sub_device(sub_device)
data.add_device(device)
result.append(data)
return result
Usage (test.py)
from battery_monitoring.conf_reader import BMReadConf
conf_obj = BMReadConf()
configs = conf_obj.get_bm_config()
for cnf in configs:
print(cnf.name) # This is name field in BatteryMonitoringServer Table.
devices = cnf.get_devices()
for dev in devices:
print(dev.baud_rate) # This is baud_rate field in second nested table.
sub_devices = dev.get_sub_devices()
for sub_dev in sub_devices:
print(sub_dev.unit) # This is unit field in third nested table.
print(sub_dev.meta_data) # This is meta_data table (fourth nested table).
I hope this would be useful.
[NOTE]:
Fourth nested table (meta_data) has a incremented key/value fields.

Related

Is there any way to add two things to a list at the same time instead of double appending-python

I have recently starting coding and so far I only have about a month and a half of experience so I'm still learning. I am taking a stab at object oriented programming but I am trying to see where I can improve my code. For the purpose of this question, specifically the last method of code. As you can see in my where_to_watch_movie method, I have an instance in which I use append twice. I have read that repeating your code twice is a bad practice, so I am wondering if there is any other way to add these items to the list. I cannot use extend, but if there is no alternative way, I can also keep my double append as there will be no penalty for repeating myself. Still would like to know for my own best practices moving forward though if anyone knows!
class Movie:
"""Movie class that takes four data members"""
def __init__(self, title, genre, director, year):
self.title = title
self.genre = genre
self.director = director
self.year = year
def get_title(self):
"""get title of the movie"""
return self.title
def get_genre(self):
"""get genre of the move"""
return self.genre
def get_director(self):
""""get director of the movie"""
return self.director
def get_year(self):
""""get year of the movie"""
return self.year
'''class StreamingService:
def __init__(self, name):
"""streaming service class that takes two data members. THe catalog is a dictionary of movies with the titles
as keys and the movie objects as the corresponding values."""
self.name = name
self.catalog = dict()
def get_name(self):
"""returns name of the streaming service"""
return self.name
def get_catalog(self):
"""returns the catalog"""
return self.catalog
def add_movie(self, mov):
"""add movie to the catalog"""
self.catalog[mov.get_title()] = mov
def delete_movie(self, title):
"""delete movie from the catalog"""
if title in self.catalog:
self.catalog.pop(title)
class StreamingGuide:
def __init__(self):
"""streaming guide"""
self.StreamingServices = []
def add_streaming_service(self, streamingservice):
"""add streaming service to the streaming services list"""
self.StreamingServices.append(streamingservice)
def delete_streaming_service(self, streamingservicename):
"""remove streaming service from the streaming services list"""
if streamingservicename in self.StreamingServices:
self.StreamingServices.remove(streamingservicename)
def where_to_watch_movie(self, title):
"""returns a list that contains the name of the movie and year, as well as the streaming service
where you can find that movie."""
list_1 = []
for item in self.StreamingServices:
if title in item.get_catalog():
list_1.append(item.get_catalog()[title].get_title() + " ("
+ str(item.get_catalog()[title].get_year()) + ")")
list_1.append(item.get_name())
if len(list_1) == 0:
return None
else:
return list_1
"""
movie_1 = Movie('The Seventh Seal', 'comedy', 'Ingmar Bergman', 1957)
movie_2 = Movie('Home Alone', 'tragedy', 'Chris Columbus', 1990)
movie_3 = Movie('Little Women', 'action thriller', 'Greta Gerwig', 2019)
movie_4 = Movie('Galaxy Quest', 'historical documents', 'Dean Parisot', 1999)
stream_serv_1 = StreamingService('Netflick')
stream_serv_1.add_movie(movie_2)
stream_serv_2 = StreamingService('Hula')
stream_serv_2.add_movie(movie_1)
stream_serv_2.add_movie(movie_4)
stream_serv_2.delete_movie('The Seventh Seal')
stream_serv_2.add_movie(movie_2)
stream_serv_3 = StreamingService('Dizzy+')
stream_serv_3.add_movie(movie_4)
stream_serv_3.add_movie(movie_3)
stream_serv_3.add_movie(movie_1)
stream_guide = StreamingGuide()
stream_guide.add_streaming_service(stream_serv_1)
stream_guide.add_streaming_service(stream_serv_2)
stream_guide.add_streaming_service(stream_serv_3)
stream_guide.delete_streaming_service('Hula')
search_results = stream_guide.where_to_watch_movie('Little Women')"""

Anaconda Spyder - Class Attributes Autocompletion

I have a couple of Classes defined.
Both of these classes take a json file as input, and extract the data into a class instance, and places them into a dictionary.
So all of my EmployeeProfile instances are stored in a dictionary called SP, with the employees email as the key, and the class instance as the value.
All of my RiskProfile instances are stored in a dictionary called RISKS, with the risk_ID as the key and the class instance as the value.
class EmployeeProfile:
def __init__(self, profile):
self.displayname = profile.get('displayName')
self.email = profile.get('email')
self.firstname = profile.get('firstName')
self.surname = profile.get('surname')
self.fullname = profile.get('fullName')
self.costcode = profile.get('work').get('custom')\
.get('Cost Category_t9HHc')
self.title = profile.get('work').get('title')
self.department = profile.get('work').get('department')
self.city = profile.get('work').get('site')
self.id = profile.get('work').get('employeeIdInCompany')
self.manageremail = ''
self.costline = 'N/A'
self.groups = {}
self.attest = {}
class RiskProfile:
def __init__(self, risk_profile):
self.ID = risk_profile.get('ID')
self.key = risk_profile.get('Key')
self.name = risk_profile.get('Name')
self.description = risk_profile.get('Description', '')
self.owner = risk_profile.get("Owner_DisplayName")
self.assignedto = risk_profile.get("AssignedTo_DisplayName")
self.email = None
self.costline = ''
self.notes = ''
self.assessmentlevel = int(risk_profile.get("AssessmentLevel"))
self.rating = ''
self.workflow = risk_profile.get('WorkflowState')
Now when I do something like:
for profile in SP:
print(SP[profile].{here i see the attribute of the class instance})
So I can see a selection of the attributes I may want to print or change etc...
print(SP[profile].department)
or
print(SP[profile].name)
However when I do the same for RiskProfile instances I do not get the list of attributes.
If I enter them manually my code still works, but does anyone know why this is not working the same way?
for profile in RISKS:
print(RISK[profile].{I never get a list of attributes})
I use Anaconda with Spyder.

Django Model.objects.last() returning second to last instance instead of the very last instance

I'm in the process of building a Django app, which is meant to be a self updating inventory app for a hypothetical restaurant. I have a model, "Purchase", which uses another model "Register" as a ForeignKey field. I have it set the reference to the last instance created of Register so that any entree purchase is linked to the currently active register at the store. The problem is that when a Purchase instance saves, it keeps referencing the second to last Register object instead of the last.
Here is the current model code for those two models:
class Register(models.Model):
daily_bank = models.FloatField(default=500)
amount_spent = models.FloatField(default=0)
amount_made = models.FloatField(default=0)
date = models.DateField(default=date.today)
def sales(self):
lst = []
for p in self.purchase_set.all():
if p.menu_item not in lst:
lst.append([p.menu_item.title, 1])
else:
for entry in lst:
if entry[0] == p.menu_item.title:
entry[1] = entry[1] + 1
return lst
def profit(self):
if self.id > 1:
return self.daily_bank - Register.objects.get(id=self.id-1).daily_bank
else:
return self.daily_bank - 500
def last(self):
return self == Register.objects.last()
class Purchase(models.Model):
menu_item = models.ForeignKey(MenuItem, on_delete=SET_NULL, null=True)
time = models.DateField(default=datetime.now)
item_name = models.CharField(max_length=100)
register = models.ForeignKey(Register, on_delete=CASCADE, default=Register.objects.last())
def save(self, *args, **kwargs):
self.item_name = self.menu_item.title
if self.pk is None:
for i in self.menu_item.reciperequirment_set.all():
if i.menu_item == self.menu_item:
i.ingredient.quantity -= i.required_amount
i.ingredient.save()
super(Purchase, self).save(*args, **kwargs)
I also have a Signal going on in the background when a new Purchase is made if that might be part of the issue?
#receiver(post_save, sender=Purchase)
def sale(sender, instance, created, **kwargs):
if created:
n = Register.objects.last()
n.daily_bank += instance.menu_item.price
n.amount_made += instance.menu_item.price
n.save()
else:
pass
Additionally this is the function I created inside another model, MenuItem, that is running in the background to provide the Purchase count for that Register
def sales(self):
count = 0
for i in self.purchase_set.all():
if i.register == Register.objects.order_by("id").last():
count += 1
count = str(count)
return count
Any ideas why Register.objects.last() isn't returning the actual last instance?

"TypeError :super() takes at least 1 argument (0 given) " how to solve this i have used argument as a super class name but it didn't worked

students = []
class Student:
school_name = 'Maharshi Science school'
def __init__(self,name,student_id=336):
self.name = name
self.student_id= student_id
students.append(self)
def __str__(self):
return "student: " + self.name
def get_name_capitalize(self):
return self.name.capitalize()
def get_school_name(self):
return self.school_name
class HighschoolStudent(Student):
school_name = 'Maharshi High School'
def get_school_name(self):
return "This is a high school student"
def get_name_capitalize(self):
original_value = super().get_name_capitalize()
return original_value + "-HighschoolStudent"
chirag = HighschoolStudent('chirag')
print(chirag.get_name_capitalize())
This error will only occur if you are using Python 2. To fix this, replace
super().get_name_capitalize()
with
super(HighschoolStudent, self).get_name_capitalize()
If you upgrade to Python 3, your code should work fine.
You are getting the error due to Python 2. Please try the below code:
students = []
class Student(object):
school_name = 'Maharshi Science school'
def __init__(self,name,student_id=336):
self.name = name
self.student_id= student_id
students.append(self)
def __str__(self):
return "student: " + self.name
def get_name_capitalize(self):
return self.name.capitalize()
def get_school_name(self):
return self.school_name
class HighschoolStudent(Student):
school_name = 'Maharshi High School'
def get_school_name(self):
return "This is a high school student"
def get_name_capitalize(self):
original_value = super(HighschoolStudent, self).get_name_capitalize()
return original_value + "-HighschoolStudent"
chirag = HighschoolStudent('chirag')
print(chirag.get_name_capitalize())
Output:
Chirag-HighschoolStudent
There are two changes in this:
class Student --> class Student(object)
Passing your class name as input in super as mandated by Python 2

printing objects in python

I'm trying to print these car_object[objectname] objects, but not sure how to do it....
I also have a Cars class. When I do print(car_object[objectname]) I get ObjectmeA160
<__main__.Cars object at 0x027FB970>. what am I doing wrong?
def __iter__(self):
car_object = {}
cursor = self._db.execute('SELECT IDENT, MAKE, MODEL, DISPLACEMENT,
POWER, LUXURY FROM CARS')
for row in cursor:
car_object = {}
objectname = 'Object'+str(row['IDENT'])
car_object[objectname] = Cars(ident = row['IDENT'], make = row['MAKE'],
model = row['MODEL'], disp = row['DISPLACEMENT'], power = row['POWER'], luxury = row['LUXURY'])
print(car_object[objectname])
yield dict(row)
class Cars:
def __init__(self, **kwargs):
self.variables = kwargs
def set_Variable(self, k, v):
self.variables[k] = v
def get_Variable(self, k):
return self.variables.get(k, None)
The <__main__.Cars object at 0x027FB970> is the standard string for custom objects that do not implement their own .__str__() hook. You can customize it by implementing that method:
class Cars:
# ....
def __str__(self):
return 'Car instance with variables: {!r}'.format(self.variables)

Categories

Resources