Autofill database column after form submission in django - ajax

Using Django 2.0 I have a model class named Book that asks for title, author, year but I have another column in that row that requires for a unique id based on the authors name, book title, and random numbers. This is my model
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=50)
year = models.PositiveSmallIntegerField()
identification = models.CharField(max_length=50, blank=True)
holder = models.ForeignKey('Person', related_name='book_holder', on_delete=models.PROTECT(), null=True, blank=True)
available = models.BooleanField(default=True, blank=True)
overdue = models.BooleanField(default=False, blank=True)
and it will be used in a form that only asks for the title, author, and year but what im looking for is how can i fill the identification column after the user submits the form. So for example if the user enters Harry Potter for the title and J. K. Rowling for the author, I want identification to have a value of a combination of both plus an eight digit random number at the end something like JH28194637 but I also need this column to be unique for every book so if i had to of the same Harry Potter books, I would need both to be different so one could be JH28194637 while the other one could be JH39287104. I will be using ajax to submit my form and I was thinking of maybe having a variable in my javascript that builds my identification when the user fills in the author and title fields and then passing it to my ajax call. Would that be the best way? But then how would I be able to check if the variable value already exists in the database or what would be the best way to do this task.

Since the two other fields are subject to change, and I assume that your identification field will also need to change, in terms of a unique integer you can always use that books model ID to make things simpler (unless you need to specify a particular id for certain books).
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=50)
year = models.PositiveSmallIntegerField()
holder = models.ForeignKey('Person', related_name='book_holder', on_delete=models.PROTECT(), null=True, blank=True)
available = models.BooleanField(default=True, blank=True)
overdue = models.BooleanField(default=False, blank=True)
#property
def identification():
a = self.author[:1].upper()
t = self.title[:1].upper()
id = str(self.id.zfill(10))
return a+t+id

Related

Can I access a specific field value from an object through accessing by the related name, in Django?

I'm making a vote app (Django rest framework), where users can post content and have it voted on through two options. The Vote modelVote model code has a ForeignKey field to the Post model, with the related name attribute "votes". The vote model also has a field named 'option', where choices 'option1' and 'option2' can be selected.
My goal is to count the total number of votes on a post, number of option1 votes and number of option2 votes.
I've been able to count the number of votes on a post through:
queryset = Post.objects.annotate(
votes_count=Count('votes', distinct=True),
)
Post views
I am unsure how to count the number of option1 and option2 votes, separately.

SQFlite Database Order (ASC, DESC, Alphabetic)

I have created a SQFlite database for my app which is working very well. Basically, the app is to create a list of my client's company details. The company name appears in an Expansion Tile, and once you open the tile, you see the rest of the company's details. I know how to arrange the tiles in either descending or ascending order, but is there a way to arrange according to alphabetic order based on the company name? Thus, can one arrange the tables in SQFlite in alphabetic order instead of ASC or DESC? When my client's details are added dynamically, I want them to be arranged in alphabetic order so that it makes more sense. Thank you so much for any help.. I have tried to find a comment on this on Stackoverflow, but don't seem to be able to find one.
Ok, I managed to figure this out. My question really shows my inexperience. Anyway, Query has a orderBy property. In my database I created the following code:
Future<void> _createDB(Database db, int version) async {
await db.execute('''
CREATE TABLE todo(
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
name TEXT,
phone TEXT,
fax TEXT,
email TEXT,
street TEXT,
city TEXT,
town TEXT,
code TEXT,
isExpanded INTEGER
orderBy used to be 'id DESC'. It should simply be changed to 'title ASC'. Thus, it will order the sequence by the title in alphabetic order from top to bottom. Here is the code:
Future<List<Todo>> getTodo() async {
final db = await database;
// query the database and save as list of maps
List<Map<String, dynamic>> items = await db.query(
'todo',
orderBy: 'title ASC',
);
Thus, the correct question is not how to order in alphabetic order, but how to order based on title (which is the company name in my example) in ASCending order.

How to list/order a number of hospitals which have lat and long fields in the model on the basis of 25 km from customer's location in Django Rest?

I'm currently working in DRF and I have a data list of many hospitals which I can list. I need to order it on the basis of a 25km radius of the customer's location. Both the Hospital models and customer profiles have got latitude and longitude fields.
I think the approach you're looking for is GeoDjango, it offers you spatial support, and will allow you to define fields like:
from django.contrib.gis.db.models import PointField
class Hospital(models.Model):
coordinates = PointField(
geography=True,
null=True,
blank=True,
)
and considering your user also has a coordinates field, you could then do things like using distance_lte:
from django.contrib.gis.measure import D
hospitals_within_25_km_radius = Hospital.objects.filter(
coordinates__distance_lte=(user.coordinates, D(km=25))
)
or even filtering and ordering by which hospitals are the closest:
from django.contrib.gis.db.models.functions import Distance
hospitals_within_25_km_ordered_by_closest = Hospital.objects.annotate(
distance=Distance('coordinates', user.coordinates),
).filter(
distance__lte=25000,
).order_by(
'distance',
)

Laravel eloquent relationship one to many

I am working on three tables: product, delivery and stock. I want that when a product is delivered, its quantity in the stock table increases. So in the controller of the delivery table I wrote this code:
$produit = Produit::find($delivery['produit_id']);
$quantite = $produit->stock->quantite;
$quantite += $delivery['quantite'];
$quantite->save();
but when I make a delivery, the quantity in the stock table does not change.
Simply types in PHP is not by reference, so you have to assign the new value to the Stock object. This is assuming quantite is an integer on the Stock model, which is not totally clear in the code you provided, since you call ->save() on quantite. Remember to save the Stock model instead of quantite.
$stock = $produit->stock;
$stock->quantite = $stock->quantite + $delivery['quantite']
$stock->save();

Interpolating an argument into a variable name

I have several pages where a date is input. I want to capture the day, month and year and store them to be checked later on. Each page has its own unique ID but uses the same IDs for each field: day, month and year.
I've got this on each page where the date is captured at the moment:
#page_10_day = find(:id, 'day').value
#page_10_month = find(:id, 'month').value
#page_10_year = find(:id, 'year').value
But I'd like to do something like this:
capture_date("page_10")
def capture_date(page)
#"#{page}_day" = find(:id, 'day').value
#"#{page}_month" = find(:id, 'month').value
#"#{page}_year" = find(:id, 'year').value
end
Is there a way of just having one method to capture the date and naming objects using an argument?

Resources