generate random value form other field value in Django - django

I have a booking system for bank line :
this is my model for the customer:
class Customer(models.Model):
customer_bank = models.ForeignKey('Bank', on_delete=models.SET_NULL,related_name='coustmer_bank' ,null=True)
customer_branch = models.ForeignKey('Branch', on_delete=models.SET_NULL,related_name='coustmer_branch',null=True)
booking_id = models.CharField(max_length=120, blank= True,default=increment_booking_number)
identity_type = models.ForeignKey('IdentityType',on_delete=models.SET_NULL,related_name='identity_type',null=True)
identity_or_passport_number = models.CharField(max_length=20)
bank_account_no = models.CharField(max_length=15)
Done = models.BooleanField(default=False)
booking_date_time = models.DateTimeField(auto_now_add=True, auto_now=False)
Entrance_date_time = models.DateTimeField(auto_now_add=False, auto_now=True)# Must be modified to work with Entrance Date and Time
def __str__(self):
return self.booking_id
I need to generate a random value for booking_id field depends on bank_number and the branch_number and the Customer id so how can I do that? help please

You can overide the save method of the model
class Customer(models.Model):
customer_bank = models.ForeignKey('Bank', on_delete=models.SET_NULL,related_name='coustmer_bank' ,null=True)
customer_branch = models.ForeignKey('Branch', on_delete=models.SET_NULL,related_name='coustmer_branch',null=True)
booking_id = models.CharField(max_length=120, blank= True,default=increment_booking_number)
identity_type = models.ForeignKey('IdentityType',on_delete=models.SET_NULL,related_name='identity_type',null=True)
identity_or_passport_number = models.CharField(max_length=20)
bank_account_no = models.CharField(max_length=15)
Done = models.BooleanField(default=False)
booking_date_time = models.DateTimeField(auto_now_add=True, auto_now=False)
Entrance_date_time = models.DateTimeField(auto_now_add=False, auto_now=True)# Must be modified to work with Entrance Date and Time
def __str__(self):
return self.booking_id
def get_booking_id(self):
bank_number = self.bank_number
branch_number = self.branch_number
id = # logic for calculating boking ID from bank_number, branch_number and other fields accessible from self.<field_name>
return id
def save(self, *args, **kwargs):
self.booking_id = self.get_booking_id()
super(Customer, self).save(*args, **kwargs)

Related

Django models - how to assign as ForeignKey

My lab has a models.py as below:
class Book(models.Model):
isbn = models.CharField(max_length=10, unique=True)
name = models.CharField(max_length=100)
published_year = models.IntegerField()
total_qty = models.IntegerField()
current_qty = models.IntegerField()
max_duration = models.IntegerField()
author = models.ForeignKey(Author, on_delete=models.PROTECT)
category = models.ForeignKey(Category, on_delete=models.PROTECT)
def __str__(self):
return self.name
class BookCopy(models.Model):
class Status:
AVAILABLE = 1
BORROW =2
LOST = 3
barcode = models.CharField(max_length=30, unique=True)
buy_date = models.DateField(null=True, blank=True)
status = models.IntegerField()
book = models.ForeignKey(Book, on_delete=models.PROTECT)
def __str__(self):
return self.barcode
class User(models.Model):
username = models.CharField(max_length=30, unique=True)
fullname = models.CharField(max_length=100, null=True)
phone = models.CharField(max_length=10, null=True)
def __str__(self):
return self.fullname
class BookBorrow(models.Model):
class Status:
BORROWING = 1
RETURNED = 2
borrow_date = models.DateField()
deadline = models.DateField()
return_date = models.DateField(null=True)
status = models.IntegerField()
book_copy = models.ForeignKey(BookCopy, on_delete=models.PROTECT)
book_name = models.ForeignKey(Book, on_delete=models.PROTECT)
user = models.ForeignKey(User, on_delete=models.PROTECT)
And i wrote the api for borrow_book function like below:
#csrf_exempt
def muon_sach(request):
body = request.POST
username = body.get('username')
barcode = body.get('barcode')
user = User.objects.filter(username=username).first()
bookcopy = BookCopy.objects.filter(barcode = barcode).first()
if not user:
return HttpResponse(json.dumps({
'error':"Nguoi dung khong ton tai"
}))
if not bookcopy:
return HttpResponse(json.dumps({
'error':"ma sach khong ton tai"
}))
book_borrow = BookBorrow()
# resp = []
book_borrow.user = user
book_borrow.book_copy = bookcopy
book_borrow.borrow_date = datetime.now()
book_borrow.deadline = datetime.now() + timedelta(days=bookcopy.book.max_duration)
book_borrow.status = BookBorrow.Status.BORROWING
book_borrow.book_name = bookcopy.book.name
book_borrow.save()
bookcopy.status = BookCopy.Status.BORROW
bookcopy.save()
bookcopy.book.current_qty -=1
bookcopy.book.save()
return HttpResponse(json.dumps({'success':True}))
however when i test with postman (give username and barcode), it gets the error
xxx "BookBorrow.book_name" must be a "Book" instance."
Could you please advise where incorrect and assist me correct it ? Appreciate for any assist
You have to do the following:
#csrf_exempt
def muon_sach(request):
# ... more code here
bookcopy = BookCopy.objects.filter(barcode = barcode).first()
book_borrow.book_name = bookcopy.book
book_borrow.save()
# ... more code here
return HttpResponse(json.dumps({'success':True}))
So in the definition of your model you can see that book_name has the following structure:
class BookBorrow(models.Model):
# ... More code here
book_name = models.ForeignKey(Book, on_delete=models.PROTECT)
user = models.ForeignKey(User, on_delete=models.PROTECT)
It is clear that BookBorrow.book_name must accept a Book instance. So when you pass in you code book_borrow.book_copy = bookcopy it is passing a BookCopy instance so that's the error.
borrow_copy.book is the appropiate.
You have specified book_name to be a Foreign Key to Book, and you try to assign to it the book.name value.
Either you need to set this field as a CharField or you need to rename the field from book_name to book and use book_borrow.book = bookcopy.book

django models getting queryset

how to get status_updation and status_date respect to the order_number
class customer_database(models.Model):
customer_id = models.CharField(max_length=20, unique=True)
customer_name = models.CharField(max_length=20)
customer_email = models.EmailField()
def __str__(self):
return self.customer_id
class order_database(models.Model):
order_number = models.CharField(max_length=10, unique=True, primary_key=True)
order_timestamp = models.DateTimeField()
order_consignment_number = models.CharField(max_length=20)
order_customer = models.ForeignKey(customer_database, on_delete=models.CASCADE)
def __str__(self):
return self.order_number
class track_database(models.Model):
order_status = models.ForeignKey(order_database, on_delete=models.CASCADE)
status_updation = models.CharField(max_length=30)
status_timestamp = models.DateTimeField()
def __str__(self):
return self.status_updation
Try
query_order_number = '1234'
tracker = track_database.objects.filter(order_status.order_number = query_order_number)
print(tracker.status_updation)
print(tracker.status_timestamp)
Let me know if this doesn't work
Or you could go via the order number:
query_order_number = '1234'
order = order_database.objects.filter(order_number = query_order_number)
print(order.track_database.status_updation)
print(order.track_database.status_timestamp)

using "primary" field in django model

i have two models: Address and Phone. Inside each model, rests a "Default" boolean field. What I need it to do, is if I submit a True answer in a form, then all other records must be set to False for that user.
How do I accomplish this?
class Address (models.Model):
User = models.ForeignKey(User)
Primary = models.BooleanField(default=True)
Street = models.CharField(max_length=500)
City = models.CharField(max_length=50)
State = models.CharField(max_length=40)
Zip = models.CharField(max_length=20)
County = models.CharField(max_length=20)
Country = models.CharField(max_length=50, default="United States")
Latitude = models.FloatField(null=True, blank=True)
Longitude = models.FloatField(null=True, blank=True)
class Meta:
verbose_name_plural = "Addresses"
def __str__(self):
primary = 'PRIMARY Address for ' if self.Primary else 'Address for '
return primary + self.User.first_name + ' ' + self.User.last_name
def save(self, *args, **kwargs):
geolocator = Nominatim()
location = geolocator.geocode("{} {}, {}, {}".format(self.Street, self.State, self.Zip, self.Country))
self.Latitude = location.latitude
self.Longitude = location.longitude
super(Address, self).save(args, *kwargs)
class Phone (models.Model):
User = models.ForeignKey(User)
Primary = models.BooleanField(default=True)
Country_Code = models.CharField(max_length=5, default="001")
Area_Code = models.CharField(max_length=5, blank=True, null=True)
Number = models.CharField(max_length=20, blank=True, null=True)
def __str__(self):
return self.Country_Code + "-" + self.Area_Code + "-" + self.Number
You can use post_save signal or override save method. Following is a simple snippet. If you want to keep consistent, put the these queries in a transaction.
def save(self, *args, **kwargs):
geolocator = Nominatim()
location = geolocator.geocode("{} {}, {}, {}".format(self.Street, self.State, self.Zip, self.Country))
self.Latitude = location.latitude
self.Longitude = location.longitude
super(Address, self).save(args, *kwargs)
Address.objects.exclude(id=self.id).update(Primary=False)

Django ValueError when trying to save ManyToMany Values from a Form

I get the error "" needs to have a value for field "dataset" before this many-to-many relationship can be used." when trying to assign values to a ManyToMany field in my views. I've looked at many related questions here on SO that say I must save my Dataset object first. I think I am doing that...what is going wrong?? My database already contains four Subject items.
models.py
class Subject(TimeStampedModel):
subject_type = models.CharField(max_length=128, blank=False)
def __unicode__(self):
return self.subject_type
class Dataset(TimeStampedModel):
dataset_id = models.CharField(max_length=256)
dataset_doi = models.CharField(max_length=15)
dataset_name = models.CharField(max_length=256, blank=False)
dataset_description = models.TextField(blank=False)
lab = models.CharField(max_length=256, blank=False)
biological_sample = models.CharField(max_length=256, blank=False)
subject_type = models.ManyToManyField('Subject', related_name='datasets', blank=True)
date_collected = models.DateField(blank=True)
collection_facility = models.ManyToManyField('CollectionFacility', related_name='datasets', blank=True)
processing_notes = models.TextField(blank=True)
release_date = models.DateField()
release_asap = models.BooleanField()
pdb_code = models.CharField(max_length=256, blank=True)
publication_link = models.URLField(blank=True)
def create_name(self):
self.dataset_name = "%s %s" % (self.biological_sample, self.lab)
def save(self, *args, **kwargs):
self.dataset_id = self.id
def __unicode__(self):
return "%s : %s" % (self.dataset_name, self.dataset_id)
forms.py RegistrationForm:
class RegistrationForm(forms.Form):
subject_type = forms.ModelMultipleChoiceField(
label="Subject",
queryset = Subject.objects.all(),
widget=forms.CheckboxSelectMultiple(),
required = True,
)
views.py
def create_registration(form):
dataset = Dataset()
dataset.DOI = "preUpload"
dataset.lab = form.cleaned_data['lab']
dataset.biological_sample = form.cleaned_data['sample']
dataset.resource_type = form.cleaned_data['dataset_type']
dataset.dataset_description = form.cleaned_data['dataset_description']
dataset.date_collected = form.cleaned_data['date_collected']
dataset.release_date = form.cleaned_data['release_date']
dataset.release_asap = form.cleaned_data['release_asap']
if form.cleaned_data['pdb_code']:
dataset.pdb_code = form.cleaned_data['pdb_code']
if form.cleaned_data['publication_link']:
dataset.publication_link = form.cleaned_data['publication_link']
dataset.create_name()
dataset.save() # I don't think this save is working?
subjects = form.cleaned_data['subject_type']
dataset.subject_type = [x for x in subjects]
for facility in form.cleaned_data['facility']
dataset.collection_facility.add(facility)
dataset.save()
return dataset
def registration_submit(request):
registration_form = RegistrationForm(request.POST)
if registration_form.is_valid():
registration = create_registration(registration_form)
.......
You forgot to call the original save() in the overriden Dataset.save() method.
def save(self, *args, **kwargs):
self.dataset_id = self.id
super(Dataset, self).save(*args, **kwargs)

Get Foreign Key Value

How can I get the foreign key values? I have a common vehicle model that links to the year, series, engine type, body style, transmission and drive train...all as foreign keys. I'd like to get the values of these fields for my app, but I'm stuck as to how I'd go about them. Any ideas will be highly appreciated.
class Model(models.Model):
model = models.CharField(max_length=15, blank=False)
manufacturer = models.ForeignKey(Manufacturer)
date_added = models.DateField()
def __unicode__(self):
name = ''+str(self.manufacturer)+" "+str(self.model)
return name
class Year(models.Model):
ALPHA_NUMERIC_CHOICES = (
('1', 'Numeric'),
('A', 'Alphabetic'),
)
year = models.PositiveSmallIntegerField()
position_7_char = models.CharField(max_length=1, choices=ALPHA_NUMERIC_CHOICES)
position_10 = models.CharField(max_length=1, blank=False)
def __unicode__(self):
return unicode(self.year)
class Series(models.Model):
series = models.CharField(max_length=20, blank=True)
model = models.ForeignKey(Model)
date_added = models.DateField()
def __unicode__(self):
name = str(self.model)+" "+str(self.series)
return name
class CommonVehicle(models.Model):
year = models.ForeignKey(Year)
series = models.ForeignKey(Series)
engine = models.ForeignKey(Engine)
body_style = models.ForeignKey(BodyStyle)
transmission = models.ForeignKey(Transmission)
drive_train = models.ForeignKey(DriveTrain)
def __unicode__(self):
name = ''+str(self.year)+" "+str(self.series)
return name
class Vehicle(models.Model):
stock_number = models.CharField(max_length=6, blank=False)
vin = models.CharField(max_length=17, blank=False)
common_vehicle = models.ForeignKey(CommonVehicle)
exterior_colour = models.ForeignKey(ExteriorColour)
interior_colour = models.ForeignKey(InteriorColour)
interior_type = models.ForeignKey(InteriorType)
odometer_unit = models.ForeignKey(OdometerUnit)
status = models.ForeignKey(Status)
odometer_reading = models.PositiveIntegerField()
selling_price = models.PositiveIntegerField()
purchase_date = models.DateField()
sales_description = models.CharField(max_length=60, blank=False)
def __unicode__(self):
return self.stock_numberodels.ForeignKey(CommonVehicle)
You need the actual IDs? Try something like my_vehicle_ref.series.id.
Also, I hope you know that the series attribute right there is really an instance of Series, so you could access any of it's properties, e.g., my_vehicle_ref.series.model.model.