How to increase CharField by 1 in django? - django

Here I have some field like idnumber in my Profile model.Which will be the mix of integer, text and -. Everytime new profile registers I want to keep the - and text same but want to increase integer by 1. How can I achieve that ?
user = get_object_or_404(get_user_model(), pk=pk)
if request.method == 'POST':
user_type = request.POST.get('type')
user.profile.is_approved=True
user.profile.save()
if user_type == 'Some Type': # i got stuck here
latest_profile = Profile.objects.filter(user_type='Some Type').last()
user.profile.idnumber = latest_profile.idnumber + 1 #this will probably raise the error
user.profile.save()
My model field for id number is like this
idnumber = models.Charfield(max_length=255,default="ABTX-123")
ABTX- will be same but want to increase 123 to 124 if new profile registers

You have to set idnumber as below...
idnumber = int(latest_profile.idnumber.split('-')[1]) + 1
new_idnumber = latest_profile.idnumber.split('-')[0] + '-' + str(idnumber)
user.profile.idnumber = new_idnumber

Related

Rest django checking the duplicate number

if i inserting the number 5 i want to check all the numbers before 5( like 1,2,3 and 4 )is must have inside the db ,then only can i add the number 5 ,otherwise show error. And also check is any duplication in the Db using rest django model serilaizer.
def validate_match_round(self, match_round):
if not match_round :
raise serializers.ValidationError("Enter value more than 0 ")
matchscore model
class Matchscore(TimeStampedModel):
gameevent = models.ForeignKey(GameEvent, null=True, related_name='game_event',on_delete=models.DO_NOTHING)
match_round = models.IntegerField(null=True,blank=True)
team_a = models.ForeignKey(Team,null=True,related_name='team_one',on_delete=models.DO_NOTHING)
team_a_score = models.PositiveIntegerField(null=True,blank=True)
team_b = models.ForeignKey(Team,null=True,related_name='team_two',on_delete=models.DO_NOTHING)
team_b_score = models.PositiveIntegerField(null=True,blank=True)
team_won = models.ForeignKey(Team,null=True,related_name='team', on_delete=models.DO_NOTHING)
if match_round == 1:
return match_round
match = Matchscore.objects.aggregate(Max('match_round'))
print(match)
if match_round == match["match_round__max"] + 1 :
return match_round
else:
raise serializers.ValidationError("Enter a valid match_round")
all_rounds = Matchscore.objects.filter(match_round__lte=match_round).order_by('match_round').values_list('match_round', flat=True)
Will return list of match_round values that lower or equal than match_round passed to function
all_rounds_count = Matchscore.objects.filter(match_round__lte=match_round).count()
Will return count of these rounds. and if (all_rounds_count + 1) == match_round check is what you want
And also check is any duplication in the Db using rest django model serilaizer.
To avoid keys duplication
Set unique=True for model.Field to disable round duplicates match_round = models.IntegerField(..., unique = True)
Add unique validator to serializer

Set initial values in form passing parameters (kwargs) with view

I want to prefill a form with values taken in a table.
First I pass the PK relative to the line where I wan't to get values and build the kwargs list:
views.py
def NavetteToFicheCreateView(request, pk):
navette = Navette.objects.get(id=pk)
ref = navette.id
attribute_set = navette.famille.pk
cost = navette.cost
qty = navette.qty
etat = navette.etat
etat_ebay = navette.etat.etat_ebay
ean = get_last_ean()
form = NavetteToFicheForm(
request.POST,
ref=ref,
attribute_set=attribute_set,
cost=cost,
qty=qty,
etat=etat,
etat_ebay=etat_ebay,
ean=ean,
)
[...]
then I retrieve the kwargs in the form.py and setup my initial values
class NavetteToFicheForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.ref = kwargs.pop('ref', 'noref')
self.attribute_set = kwargs.pop('attribute_set', 9999)
self.cost = kwargs.pop('cost', 0)
self.qty = kwargs.pop('qty', 0)
self.etat = kwargs.pop('etat', 0)
self.etat_ebay = kwargs.pop('etat_ebay', 9999)
self.ean = kwargs.pop('ean', 9999)
super(NavetteToFicheForm, self).__init__(*args, **kwargs)
self.fields['ref'].initial = self.ref
self.fields['attribute_set'].initial = self.attribute_set
self.fields['cost'].initial = self.cost
self.fields['qty'].initial = self.qty
self.fields['etat'].initial = self.etat
self.fields['etat_ebay'].initial = self.etat_ebay
self.fields['ean'].initial = self.ean
[...]
My problem : some fields like "ref" or "attribute_set" are foreignKeys and are not transmitted when i display the form.
For checking my values :
print(self.ref)
print(self.attribute_set)
output
34
2
noref
9999
questions :
Why does the "print" displays 2 couples of values ? This looks like as if the "noref" and "999" are taken in account.
Why if i set manually 34 and 2 values, it works ?
self.fields['ref'].initial = 34
self.fields['attribute_set'].initial = 2
There's maybe a better way of doing this but I don't know it yet .

Django validation of number from query string

Im having this code to create and add students to database.
I need to make validation of count which must be integer, only positive, equal or less 100.
Please help.
def generate_students(request):
count = request.GET.get('count')
studentslist = []
for student in range(0, int(count)):
student = Student.objects.create(first_name = fake.first_name(), last_name = fake.last_name(), age = random.randint(18,100))
studentslist.append(student)
output = ', '.join(
[f"id = {student.id} {student.first_name} {student.last_name}, age = {student.age};" for student in studentslist]
)
return HttpResponse(str(output))
The best way is likely to work with a form, since a form has a lot of validation inplace, can clean the object, and print sensical errors.
We thus can work with a simple form:
from django import forms
class CountForm(forms.Form):
count = forms.IntegerField(min_value=1, max_value=100)
then we can validate the input with:
def generate_students(request):
form = CountForm(request.GET)
if form.is_valid():
count = form.cleaned_data['count']
studentslist = [
Student.objects.create(first_name = fake.first_name(), last_name = fake.last_name(), age = random.randint(18,100))
for _ in range(count)
]
output = ', '.join(
[f'id = {student.id} {student.first_name} {student.last_name}, age = {student.age};'
for student in studentslist]
)
else:
return HttpResponse(str(form.errors))
return HttpResponse(str(output))
Note: Section 9 of the HTTP protocol
specifies that requests like GET and HEAD should not have side-effects, so you
should not change entities with such requests. Normally POST, PUT, PATCH, and
DELETE requests are used for this. In that case you make a small <form> that
will trigger a POST request, or you use some AJAX calls.

Django: How to take my query out of my for loop

I got the following code, that contains N queries:
for qty in total_qty_bought:
product_id = qty["product"]
quantity = int(qty["quantity__sum"])
try:
method_title = (
self.shipment_model.get(order_id=qty["order_id"])
.method_title.replace("Hent-selv", "")
.strip()
)
To solve the issue I tried to take the method_title query out of the for loop like this:
quantity = 0
for qty in total_qty_bought:
quantity = int(qty["quantity__sum"])
method_title = (
self.shipment_model.get(order_id=total_qty_bought[0]['order_id'])
.method_title.replace("Hent-selv", "")
.strip()
)
Note! There will be a full refrence further down, to understand the bigger picture
The issue in my solution is, that I am hard choosing which dict to enter , as I select [0] before order_id, and not in a for loop like before, would be selecting every individual item in the loop.
Is there a more sufficient way to do this? I do not see a solution without the for loop, but django debugger tool tells me it creates 2k+ queries.
CODE FOR REFRENCE
class InventoryStatusView(LoginRequiredMixin, View):
template_name = "lager-status.html"
cinnamon_form = CinnamonForm(prefix="cinnamon_form")
peber_form = PeberForm(prefix="peber_form")
pc_model = InventoryStatus
product_model = Product.objects.all()
order_item_model = WCOrderItem.objects.all()
shipment_model = WCOrderShipment.objects.all()
def get(self, request):
# Get all added objects that hasn't been deleted
objects = self.pc_model.objects.filter(is_deleted=False)
# Get all added objects that has been deleted
deleted_objects = self.pc_model.objects.filter(is_deleted=True)
# Sum all cinnamon that isn't deleted
total_cinnamon = (
self.pc_model.objects.filter(is_deleted=False)
.aggregate(Sum("cinnamon"))
.get("cinnamon__sum", 0.00)
)
# Sum all peber that isn't deleted
total_peber = (
self.pc_model.objects.filter(is_deleted=False)
.aggregate(Sum("peber"))
.get("peber__sum", 0.00)
)
# Get the amount of kilo attached to products
product_data = {}
queryset = ProductSpy.objects.select_related('product')
for productSpy in queryset:
product_data[productSpy.product.product_id] = productSpy.kilo
# Get quantity bought of each product
total_qty_bought = self.order_item_model.values(
"order_id", "product"
).annotate(Sum("quantity"))
# Get the cities from the inventory model
cities = dict(self.pc_model.CITIES)
# Set our total dict for later reference
our_total = {}
product = Product.objects.filter(
product_id__in={qty['product'] for qty in total_qty_bought}
).first()
# Check if we deal with kanel or peber as a product based on slug
index = 0
if product.slug.startswith("kanel-"):
index = 0
elif product.slug.startswith("peber-"):
index = 1
else:
pass
try:
# Sum the total quantity bought
quantity = 0
for qty in total_qty_bought:
quantity = int(qty["quantity__sum"])
# Get the inventory the order is picked from based on shipment method title
method_title = (
self.shipment_model.get(order_id=total_qty_bought[0]['order_id']) # The error
.method_title.replace("Hent-selv", "")
.strip()
)
# If the order isn't picked, but sent, use this inventory
if method_title not in cities.values():
method_title = "Hovedlager"
try:
# Get the total of kanel and peber bought
kilos = quantity * product_data[product.id]
# If there is no inventory, set it to 0 peber and 0 kanel
if method_title not in our_total:
our_total[method_title] = [0, 0]
# Combine place and kilos
our_total[method_title][index] += kilos
except KeyError as ex:
print(ex)
pass
except WCOrderShipment.DoesNotExist as ed:
print(ed)
pass
# Quantities BOUGHT! (in orders!)
print(our_total)
context = {
"cinnamon_form": self.cinnamon_form,
"peber_form": self.peber_form,
"objects": objects,
"deleted_objects": deleted_objects,
"total_cinnamon": total_cinnamon,
"total_peber": total_peber,
"our_total": our_total,
}
return render(request, self.template_name, context)
You can only do one query by using the __in operator:
shipments = self.shipment_model.get(order_id__in=list_containing_order_ids)
Then you can do a normal for loop in which you verify that condition.

How do I use data stored in django model in a calculation and then store the result of a calculation in a django model field?

I'm working on my first Django app, and I need to take the data inputted by a user in my models fields, insert it into a function that makes a calculation using that data, and then returns the value of that calculation to my model where it is then stored.
It is not essential that the result be stored in my database, however I will need to use the resulting figure later on to allow the app to determine which data to present to the user.
I have my model class in models.py:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
age = models.IntegerField(default=18)
gender = models.CharField(max_length=6, choices=gend, default='')
weight = models.IntegerField(default=0)
height = models.IntegerField(default=0)
and my function in a services.py file:
def caloriefunction():
weight = Profile.weight
height = Profile.height
age = Profile.age
isMale = Profile.gender
if isMale == "Male":
isMale = True
elif isMale == "Female":
isMale = False
else:
print("Error")
quit()
if isMale:
bmr = 66.5 + (13.75 * weight) + (5 * height) - (6.755 * age)
else:
bmr = 655.1 + (9.6 * weight) + (1.8 * height) - (4.7 * age)
bmr = round(bmr)
return bmr
How would I get the resulting value and then store it in my database or keep it to use in another piece of logic?
Would I be better off using the function in the class as a method?
Sorry if the question isn't being asked very well i'm quite a newbie.
Any help if appreciated!
Yes, you can add that as a method of Profile. And/or if you want to keep the result handy you could add another field to the profile model, and override the save method so it is recalculated whenever an instance is saved. Something like this:
def save(self, *args, **kwargs):
self.update_bmr()
super().save(*args, **kwargs)
def update_bmr(self):
if self.gender == "Male":
self.bmr = (
66.5
+ (13.75 * self.weight)
+ (5 * self.height)
- (6.755 * self.age)
)
elif self.gender == "Female":
self.bmr = (
655.1
+ (9.6 * self.weight)
+ (1.8 * self.height)
- (4.7 * self.age)
)
else:
self.bmr = None
You may need to guard against missing data.