When dynamically creating and generating Model class, modify some
properties, fill in the information required by the sub-table, the
first time can return the normal result, the second result error,
after the analysis of the second result field to retain the first
table name:
class Object:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def _model_new(cls, *args, **kwargs):
return cls(*args, **kwargs)enter code here
class ShardModel(object):
_shard_db_models = {}
temp_class = []
def __new__(cls, *args, **kwargs):
shard_key = kwargs.pop('shard_key', 0) % cls.Config.table_num
model_name = cls.__name__
model_name += '_%s' % shard_key
model_class = cls._shard_db_models.get(model_name)
if model_class is not None:
return model_class
# Deep copy attrs
attrs = dict()
attrs.update(cls.__dict__)
if 'objects' in attrs:
attrs['objects'] = attrs['objects'].__class__()
# Set table name with shard_key
meta = Object(**cls.Meta.__dict__)
meta.db_table = meta.db_table % shard_key
meta.abstract = False
attrs['Meta'] = meta
attrs['new'] = classmethod(_model_new)
attrs['__module__'] = cls.__name__
cursor = connection.cursor()
tables = [table_info.name for table_info in connection.introspection.get_table_list(cursor)]
# Create model class dynamically
model_class = type(model_name, tuple([models.Model] + list(cls.__bases__[1:])), attrs)
print(model_class)
if meta.db_table not in tables:
for cmd in ('makemigrations', 'migrate'):
exec_command(cmd, meta.app_label)
cls._shard_db_models[model_name] = model_class
return model_class
this is my model
class Nice(ShardModel):
user_id = models.IntegerField()
user_name = models.CharField(max_length=256)
password = models.CharField(max_length=256)
class Config:
table_num = 3
class Meta:
app_label = 'Test'
db_table = 'test_%s'
abstract = True
this my view
def NiceView(request):
user_id = int(request.GET.get('user_id'))
user = Nice(shard_key=user_id).objects.get(user_id=user_id)
return HttpResponse(json.dumps(model_to_dict(user)))
Here are the two times test results
url:http://127.0.0.1:8000/test?user_id=7
results:{"id": 2, "user_id": 7, "user_name": "ni", "password": "hao"};url:http://127.0.0.1:8000/test?user_id=5;error:(1054, "Unknown column 'test_1.user_id' in 'field list'")
Related
Been trying to show the created_date of the customer order on another view, kindly help much appreciated.
ListListView
class ListListView(generic.ListView):
model = HBTYList
template_name = "accounts/modals/nomodal/index.html"
paginate_by = 3
def get_queryset(self):
qs = self.model.objects.all().order_by('-id')
p_f = HbtyCustomerListFilter(self.request.GET, queryset=qs)
return p_f.qs
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['dc'] = HBTYItem.objects.filter(hbty_cust_id=self.kwargs["list_id"]) #Fix this method to show created_data
context['filter'] = HbtyCustomerListFilter(self.request.GET, queryset=self.get_queryset())
return context
ItemListView
class ItemListView(ListView):
model = HBTYItem
template_name = "accounts/modals/nomodal/todo_list.html"
paginate_by = 2
ordering = ['id']
def get_queryset(self):
return HBTYItem.objects.filter(hbty_cust_id=self.kwargs["list_id"])
def get_context_data(self):
context = super().get_context_data()
context['t_sum'] = HBTYItem.objects.filter(hbty_cust_id=self.kwargs["list_id"]).aggregate(Sum('price'))
context["hbty_list"] = HBTYList.objects.get(id=self.kwargs["list_id"])
return context
Urls.py
path("hbtylist/", views.ListListView.as_view(), name="hbtylist"),
path("list/<int:list_id>/", views.ItemListView.as_view(), name="list"),
# CRUD URL FOR HBTYCUSTOMERS
path("list/add/", views.ListCreate.as_view(), name="list-add"),
path("list/<int:pk>/delete/", views.ListDelete.as_view(), name="list-delete"),
# CRUD URL FOR HBTYCUSTOMERSAPPOINMENTS
path("list/<int:list_id>/item/add/", views.ItemCreate.as_view(),name="item-add",),
path("list/<int:list_id>/item/<int:pk>/",views.ItemUpdate.as_view(),name="item-update",),
path("list/<int:list_id>/item/<int:pk>/delete/",views.ItemDelete.as_view(),name="item-delete",),
Thank You For The Help.
I have tried creating instances of the class eachItem from a csv file, however, my code keeps crashing.
class eachItem():
pattern_iphone_7 = '.*[iI]*[pP]hone 7'
list_of_all_objects = []
def __init__(self, item_name, item_price, item_link, item_image, item_location):
self.dictionary = {}
self.dictionary['name'] = item_name
self.dictionary['price'] = item_price
self.dictionary['link'] = item_link
self.dictionary['image'] = item_image
self.dictionary['location'] = item_location
print(self.dictionary)
#self.__class__.list_of_all_objects.append(self.dictionary)
if re.match(self.__class__.pattern_iphone_7, self.dictionary['name']):
print(self.dictionary['name'])
item_iPhone_7(
self.dictionary['name'],
self.dictionary['price'],
self.dictionary['link'],
self.dictionary['image'],
self.dictionary['location'])
else:
self.__class__.list_of_all_objects.append(self.dictionary)
#classmethod
def from_csvfile(cls):
with open("scraped facebook marketplace data.csv", "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
items = list(reader)
i=0
for item in items:
print(f"Instantiated instance number: {i}")
i+= 1
eachItem(
item_name = item.get('name'),
item_price = item.get('price'),
item_link = item.get('link'),
item_image = item.get('image'),
item_location = item.get('location')
)
def __repr__(self):
return f"name: {self.dictionary['name']}, price: {self.dictionary['price']}, link: {self.dictionary['link']}, image: {self.dictionary['image']}, location: {self.dictionary['location']}"
eachItem.from_csvfile()
class item_iPhone_7(eachItem):
list_of_instances=[]
def __init__(self, item_name, item_price, item_link, item_image, item_location):
super().__init__(item_name, item_price, item_link, item_image, item_location)
item_iPhone_7.list_of_instances.append(self.dictionary)
if __name__ == "__main__":
eachItem.from_csvfile()
I am trying to do it this way because as I am trying to create instances of the class eachItem, I would also want to automatically create instances of the class item_iPhone_7. That is the reason why I try to create instance of the child class in the parent class.
How could I try to do this in a safer way, without crashing the kernel?
I am working on an ecommerce project but my OrderManager() class does not saving the instance(i think)
When i am clicking on BOOK button i am getting this error which is defined in my view
order_amount = order_obj.total * 100
AttributeError: 'NoneType' object has no attribute 'total'
But when i refresh the page error goes way and order_obj.total * 100 is calculated, But my question is why i need to refresh the page again and again when i create a new order.
Here is my models.py
class OrderQuerySet(models.query.QuerySet):
def not_created(self):
return self.exclude(status='created')
class OrderManager(models.Manager):
def get_queryset(self):
return OrderQuerySet(self.model, using=self.db)
def create_or_get_order(self, product):
created = None
obj = None
qs = self.get_queryset().filter(product=product, active=True, status='created')
if qs.count() == 1:
obj = qs.first()
else:
self.model.objects.create(product=product)
created = True
return obj, created
class Order(models.Model):
order_id = models.CharField(max_length=120, blank=True)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
total = models.PositiveIntegerField()
active = models.BooleanField(default=True)
objects = OrderManager()
class Meta:
ordering = ['-ordered_on', '-updated']
def __str__(self):
return self.order_id
def check_done(self): # check everything is correct before final checkout
order_id = self.order_id
total = self.total
if order_id and total > 0:
return True
return False
def mark_paid(self):
if self.check_done():
self.status = 'paid'
self.save()
return self.status
def pre_save_create_order_id(sender, instance, *args, **kwargs):
if not instance.order_id:
instance.order_id = unique_order_id_generator(instance)
pre_save.connect(pre_save_create_order_id, sender=Order)
def pre_save_order_total(sender, instance, *args, **kwargs):
"""calculate the product total while clicking on Book Button
(Still booking is not done you just clicked on Book button)"""
instance.total = instance.product.price
pre_save.connect(pre_save_order_total, sender=Order)
Views.py
def checkout_home_view(request, *args, **kwargs):
order_obj = None
order_amount = None
order_currency = None
order_id = None
slug = kwargs['slug']
product = Product.objects.get(slug=slug)
if product is not None:
# ****************** Here is problem ******************************
order_obj, order_create = Order.objects.create_or_get_order(product)
''' HERE I AM GETTING order_obj as None BUT WHEN I REFRESH ERROR GOES WAY '''
print('order_obj', order_obj) # printing None initally
order_amount = order_obj.total * 100
order_currency = 'INR'
order_id = order_obj.order_id
if request.method == 'POST':
'check that booking is done'
is_prepared = order_obj.check_done() # check_done() defined in Order model
if is_prepared:
client = razorpay.Client(auth=("xxx", "xxx"))
payment = client.order.create(dict(amount=order_amount, currency=order_currency))
if payment:
order_obj.mark_paid() # mark_paid() defined in Order model
order_obj.save()
class OrderManager(models.Manager):
...
def create_or_get_order(self, product):
created = None
obj = None
qs = self.get_queryset().filter(product=product, active=True, status='created')
if qs.count() == 1:
obj = qs.first()
else:
# -------------- catch the returned obj and return --------------
obj = self.model.objects.create(product=product)
created = True
return obj, created
I have defined an attribute in a custom class, but I keep receiving an AttributeError when I try to access it.
class SMainWindow(QMainWindow):
def __init__(self):
# Constructor
super(SMainWindow, self).__init__()
self.myapp = PyQtApp()
self.layout = QVBoxLayout()
self.label_text = ''
self.settings = scrudb.retrieve_settings('current')
self.competition = self.retrieve_competition()
self.set_competition(self.competition.id)
self.label = QLabel(self.label_text)
self.button_scrutineer = QPushButton('Scrutineer Competition')
self.button_comps = QPushButton('Change Competition')
self.button_comp = QPushButton('Edit Competition Details')
self.button_dancers = QPushButton('Add/Edit Competitors')
self.button_judges = QPushButton('Add/Edit Judges')
self.button_dancerGroups = QPushButton(
'Define Competitor Groups & Dances')
self.button_import = QPushButton('Import CSV')
self.button_delete = QPushButton('Delete Competition')
self.button_exit = QPushButton('Exit')
self.button_comps.clicked.connect(self.select_competition)
self.button_delete.clicked.connect(self.delete_competition)
self.button_exit.clicked.connect(self.exit_app)
if (self.competition == None):
self.disable_buttons()
self.layout.addWidget(self.label)
self.layout.addWidget(self.button_scrutineer)
self.layout.addWidget(self.button_comps)
self.layout.addWidget(self.button_comp)
self.layout.addWidget(self.button_dancers)
self.layout.addWidget(self.button_judges)
self.layout.addWidget(self.button_dancerGroups)
self.layout.addWidget(self.button_import)
self.layout.addWidget(self.button_delete)
self.layout.addWidget(self.button_exit)
self.myapp.setLayout(self.layout)
def set_competition(self, comp_id):
self.competition = scrudb.retrieve_competition(comp_id)
if (self.competition != None):
self.label_text = ('<center>Competition:<br><strong>%s</strong><br>%8s<br>%s</center>' % (self.competition.name, self.get_formatted_date(self.competition.eventDate), self.competition.location))
self.label.setText(self.label_text)
self.settings.lastComp = self.competition.id
scrudb.set_settings(self.settings)
return self.competition
else:
self.label_text = ('<center>No Competition Selected</center>')
return None
File "/Users/majikpig/mu_code/src/main/python/scruinterface1.py", line 182, in set_competition
self.label.setText(self.label_text)
AttributeError: 'SMainWindow' object has no attribute 'label'
You need to change order of fields ... in set competition function you try to access field, which you haven't defined yet.
self.set_competition(self.competition.id)
self.label = QLabel(self.label_text)
I'm trying to build a logging application that stores date, exercise type, duration and comments in a database. It renders the form as i expect it but it does not create the database table from my base class. I just got stuck and hope anyone can help me what's going wrong.
CHOICES = [
(None, 'Choose Exercise'),
('Aerobics', 'Aerobics'),
('Box & Kick', 'Box & Kick'),
('Circle Training', 'Circle Training'),
('Core', 'Core'),
('Afrodance', 'Afro Dance'),
('HIT', 'HIT'),
('StepUp', 'StepUp'),
('Zumba', 'Zumba')]
class AerobicExercise(models.Model):
date = models.DateField(default='YYYYMMDD')
duration = models.DurationField()
comment = models.TextField(blank=True)
exercise = models.CharField(choices=CHOICES, max_length=20)
def __str__(self):
return self.exercise
class SplitDurationWidget(forms.MultiWidget):
def __init__(self, attrs=None):
widgets = (forms.NumberInput(attrs=attrs),
forms.NumberInput(attrs=attrs),
forms.NumberInput(attrs=attrs))
super(SplitDurationWidget, self).__init__(widgets, attrs)
def decompress(self, value):
if value:
hours = value.seconds // 3600
minutes = (value.seconds % 3600) // 60
seconds = value.seconds % 60
return [int(value.days), int(hours), int(minutes), int(seconds)]
return [0, 0, 0, 0]
class Duration(MultiValueField):
widget = SplitDurationWidget
def __init__(self, *args, **kwargs):
fields = (
forms.IntegerField(),
forms.IntegerField(),
forms.IntegerField(),
)
super(Duration, self).__init__(
fields=fields,
require_all_fields=True, *args, **kwargs
)
def compress(self, data_list):
if len(data_list) == 3:
return timedelta(
hours=int(data_list[0]),
minutes=int(data_list[1]),
seconds=int(data_list[2])
)
else:
return timedelta(0)
class AerobicForm(ModelForm):
def __init__(self, *args, **kwargs):
super(AerobicForm, self).__init__(*args, **kwargs)
self.fields['duration'] = Duration()
date = forms.DateField(initial=datetime.date.today())
class Meta:
model = AerobicExercise
fields = '__all__'
localized_fields = ('date',)
widgets = {
'comment': Textarea(attrs={'placeholder': 'The highlight of this workout was...'}),
}