Peewee Meta class inherence - orm

I am struggling with the following:
from my_db_definition import db
from peewee import *
class A(Model):
class Meta:
database=db
table_name = 'random'
class B(A):
pass
when running
print(A._meta.table_name)
print(B._meta.table_name)
random
b
My question is now, why is the table name changed in this case, and can this be prevented? I am completely confused

http://docs.peewee-orm.com/en/latest/peewee/models.html#model-options-and-table-metadata
The docs list which options are inherited and which are not.
Only certain attributes are passed to the subclass via the inner "Meta" class. It's purpose is 1) namespacing, and 2) provide conventions around DRY code.
table name is not inherited because presumably you only want one class-per-table, whereas database is inherited because it makes sense to only declare that once.

Related

OOP - Best way to populate Object

I try to follow OOP and S.O.L.I.D for my code and came across a topic where I'm not sure what's the best way to align it with OOP.
When I have an Object with different properties, what's the ideal way to populate those properties?
Should the Object if possible populate them?
Should separate code assign the values to the properties?
I have the following example (Python), which I created based on how I think is the best way.
The Object has methods that will populate the properties so if you instantiate the Object, in this case an Account with and Id, it should automatically populate the properties since they can be retrieved with the ID using DB and API.
class Account:
def __init__(self, account_id):
self.id = account_id
self.name = None
self.page = Page(self.id)
def populate(self):
self.get_name()
def get_name(self):
''' Code to retrieve Account name from DB with account_id '''
self.name = <NAME>
class Page:
def __init__(self, account_id):
self.id = 0
self.name = None
self.user_count = 0
self.populate()
def populate():
self.get_id()
self.get_name()
self.get_user_count()
def get_id(self):
''' Code to retrieve Page Id from DB with account_id '''
self.id = <Page_ID>
def get_name(self):
''' Code to retrieve Account name from DB with account_id '''
self.name = <NAME>
def get_user_count(self):
''' Code to retrieve user_count from API with page_id '''
self.user_count = <user_count>
So instead of doing something like:
account = Account()
account.id = 1
account.name = function.to.get.account.name()
account.page = Page()
account.page.id = 1
I will have it managed by the class itself.
The problem I could see with this is the dependency on the DB and API classes/methods which go against S.O.L.I.D (D - Dependency Inversion Principle) as I understand.
For me it makes sense to have the class handle this, today I have some similar code that would describe the Object and then populate the Object properties in a separate Setup class, but I feel this is unnecessary.
The articles I found for OOP/S.O.L.I.D did not cover this and I didn't really find any explanation on how to handle this with OOP.
Thanks for your help!
Michael
Your design seems fairly ok. Try having a look # Builder Pattern and Composite pattern. And for your question on violation of D principle.
The problem I could see with this is the dependency on the DB and API classes/methods which go against S.O.L.I.D (D - Dependency Inversion Principle) as I understand.
The dependencies are already abstracted into separate components I guess. It is the responsibility of that component to give the data you needed per the contract. Your implementation should be independent of the what that component internally does. A DAO layer for accessing DB and Data APIs can help you achieve this.
The dependency then your system will have is the DAO component. That can be injected with different ways. There are frameworks available to help you here or you can control the creation of objects and injections when needed with some combinations of factory, builder and singleton patterns. If it is single DB instance or LogFile you may also consider using Singleton to get the component.
Hope it helps!
In looking at SOLID and OOP the key is to analyze what it is your doing and separate out the various elements to make sure that they do not end up mixed together. If they do the code tends to become brittle and difficult to change.
Looking at the Account class several questions need to be answered when considering the SOLID principles. The first is what is the responsibility of the Account class? The Single Responsibility Principle would say there should be one and only one reason for it to change. So does the Account class exist to retrieve the relevant information from the DB or does it exist for some other purpose? If for some other purpose then it has multiple responsibilities and the code should be refactored so that the class has a single responsibility.
With OOP typically when retrieving data from a DB a repository class is used to retrieve information from the DB for an object. So in this case the code that is used to retrieve information from the DB would be extracted out form the Account class and put in this repository class: AccountRepository.
Dependency Inversion means that the Account class should not depend explicitly on the AccountRepository class, instead the Account class should depend on the abstraction. The abstraction would be an interface or abstract class with no implementation. In this case we could use an interface called IAccountRepository. Now the Account class could use either an IoC container or a factory class to get the repository instance while only having knowledge of IAccountRepository

How to call remove_column on SALV table?

I want to execute the method remove_column on an instance of cl_salv_column_table but because of its visibility level, I am not able to do so.
Plan:
I already tried inheriting from cl_salv_columns_list and then perform the call inside the remove-method:
CLASS lcl_columns_list DEFINITION INHERITING FROM CL_SALV_COLUMNS_LIST.
PUBLIC SECTION.
METHODS:
remove IMPORTING iw_colname TYPE string.
ENDCLASS.
But apparently my casting knowledge got rusty as I'm not able to figure out an appropriate solution.
This is my current hierarchy - the red arrows show the way I would have to take:
My approach looks like this:
DATA lo_column_list TYPE REF TO lcl_columns_list.
lo_column_list ?= CAST cl_salv_columns_list( lo_columns ).
But it fails with:
CX_SY_MOVE_CAST_ERROR
Source type: \CLASS=CL_SALV_COLUMNS_TABLE
Target type: "\PROGRAM=XXX\CLASS=LCL_COLUMNS_LIST"
Background:
My task is to select all columns of 3 tables (which would be done like SELECT t1~*, t2~*, t3~* ...) as long as their names don't conflict (e.g. field MANDT should only be displayed once). This would require defining a very big structure and kick the size of the selection list to a maximum.
To avoid this, I wanted to make use of the type generated by my inline-declaration. Hiding the individual columns via set_visible( abap_false ) would still display them in the layout manager - which looks really ugly.
Is there any other way to accomplish my target?
Use set_technical( abap_true ) to hide the columns entirely. As for your approach - sorry, inheritance does not work that way - in no statically typed object oriented language that I know. You can't 'recast' an instantiated object to a different class. You would need to modify the framework extensively to support that.

Ignore a base model in a Django ORM query

I have these models:
class Foo(models.Model):
some_field = models.CharField()
class Meta:
pass
class Bar(Foo):
some_other_field = models.CharField()
class Meta:
pass
The example is simplified, in reality both models have a lot of fields.
When I query Bar, the Django ORM creates a query containing an inner join with Foo.
I don't need the information in Foo.
Question: Is there a way to query Bar without an inner join with Foo?
I realize that removing Bar extending Foo and making it a foreign key would be a better way to solve this problem. However, there's a lot of legacy code relying on this so I'd prefer a quick solution until I have the time and guts to refactor legacy parts of the app.
I also realize I can write an SQL query myself, but I'd prefer a solution that uses the ORM.
The way I've done it is to use a new unmanaged model for this instance
class SkinnyBar(models.Model):
some_other_field = models.CharField()
class Meta:
managed = False
db_table = "app_bar"
This will allow you to use the ORM.
If you want to avoid the duplication you could try adding most of your properties and methods to a meta class
class BaseBar(models.Model):
some_other_field = models.CharField()
def some_common_method(self):
return True
class Meta:
abstract = True
class Bar(BaseBar, Foo):
def some_method_that_requires_foo(self):
return self.some_field == 1
class SkinnyBar(BaseBar):
class Meta:
managed = False
db_table = "app_bar"
The proper way of doing this is making the Foo model abstract by adding abstract = True in the Meta. In your case, some_field is in the app_foo table and the join is needed in order to create the Bar object completely. If you don't need some_field, you can always drop to raw SQL. But in order to retrieve it, you must join app_bar and app_foo tables.
Interesting issue you have.
The inner join on it's own shouldn't be that big of a deal so long as your queries are setup appropriately. What is the main reason for trying to limit it, performance I assume? Can you post some code of how you're trying to work on these models?
I'm not positive this would work, but you could always look into using the 'defer' function on your queryset. This function is really only for advanced use-cases, and may not apply here. In essence, defer doesn't try to query the fields you specify. if you defer'some_field', perhaps it won't do the join. The downside is that as soon as you try to access 'some_field' from the object, it will perform a query (iteration will cause n extra queries).

When can a reference's type differ from the type of its object?

Yesterday I was asked a question in an interview:
Suppose class A is a base class, and class B is derived class.
Is it possible to create object of:
class B = new class A?
class A = new class B?
If yes, then what happen?
Objects of type B are guaranteed to also be objects of type A. This type of relationship is called "Is-a," or inheritance, and in OOP it's a standard way of getting polymorphism. For example, if objects of type A have a method foo(), objects of type B must also provide it, but its behavior is allowed to differ.
The reverse is not necessarily true: an object of type A (the base class) won't always be an object of type B (the derived class). Even if it is, this can't be guaranteed at compile-time, so what happens for your first line is that the code will fail to compile.
What the second line does depends on the language, but generally
Using a reference with the base type will restrict you to only accessing only members which the base type is guaranteed to have.
In Java, if member names are "hidden" (A.x exists and so does B.x, but they have different values), when you try to access the member you will get the value which corresponds to the type of the reference rather than the type of the object.
The code in your second example is standard practice when you are more interested in an API than its implementation, and want to make your code as generic as possible. For instance, often in Java one writes things like List<Integer> list = new ArrayList<Integer>(). If you decide to use a linked list implementation later, you will not have to change any code which uses list.
Take a look at this related question: What does Base b2 = new Child(); signify?
Normally, automatic conversions are allowed down the hierarchy, but not up. That is, you can automatically convert a derived class to its base class, but not the reverse. So only your second example is possible. class A = new class B should be ok since the derived class B can be converted to the base class A. But class B = new class A will not work automatically, but may be implemented by supplying an explicit conversion (overloading the constructor).
A is super class and B is a SubClass/Derived Class
the Statement
class A = new class B is always possible and it is called Upcasting because you are going Up in terms of more specific to more General
Example:
Fruit class is a Base Class and Apple Class is Derived
we can that Apple is more specific and must possess all the quality of an Fruit
so you can always do UPcasting where as
DownCasting is not always possible because Apple a=new Fruit();
A fruit can be a Apple or may it is not

OOP: class inheritance to add just one property vs constructor argument

I'm new to OOP and I'm in the following situation: I have something like a report "Engine" that is used for several reports, the only thing needed is the path of a config file.
I'll code in Python, but this is an agnostic question.So, I have the following two approaches
A) class ReportEngine is an abstract class that has everything needed BUT the path for the config file. This way you just have to instantiate the ReportX class
class ReportEngine(object):
...
class Report1(ReportEngine):
_config_path = '...'
class Report2(ReportEngine):
_config_path = '...'
report_1 = Report1()
B) class ReportEngine can be instantiated passing the config file path
class ReportEngine(object):
def __init__(self, config_path):
self._config_path = config_path
...
report_1 = ReportEngine(config_path="/files/...")
Which approach is the right one? In case it matters, the report object would be inserted in another class, using composition.
IMHO the A) approach is better if you need to implement report engines that are different from each other. If your reports are populated using different logic, follow this approach.
But if the only difference among your report engines is the _config_path i think that B) approach is the right one for you. Obviosly, this way you'll have a shared logic to build every report, regardless the report type.
Generally spoken, put everything which every Report has, in the superclass. Put specific things in the subclasses.
So in your case, put the _config_path in the superclass ReportEngine like in B) (since every Report has a _config_path), but instanciate specific Reports like in A), whereas every Report can set its own path.
I don't know Python, but did a quick search for the proper syntax for Python 3.0+, I hope it makes sense:
class ReportEngine(object):
def __init__(self, config_path):
self._config_path = config_path
def printPath(self):
print self._config_path
...
class Report1(ReportEngine):
def __init__(self):
super().__init__('/files/report1/...')
Then a
reportObj = Report1()
reportObj.printPath()
should print
'/files/report1/...'
Basically the main difference is that approach A is more flexible than B(not mutual change in one report does not influence other reports), while B is simpler and clearer (shows exactly where the difference is) but a change affecting one report type would require more work. If you are pretty sure the reports won't change in time - go with B, if you feel like the differences will not be common in the future - go with A.