I am trying to create a lyrics app in Django. And I have come up with this model. The site will be community based, that is people will submit lyrics once they input the proper captcha challenge etc.. That comes at a price I guess, for example how can I enforce the relationship between Song and Album?
But most importantly is my design sound? Is there a need for more models?
class Artist(models.Model):
first_name = models.CharField(max_length=50, null = False, blank = True)
middle_name = models.CharField(max_length=50, null = True, blank = True)
last_name = models.CharField(max_length=50, null = True, blank = True)
biography = models.TextField(null=True, blank = True)
comment = models.TextField(null=True, blank = True)
thumb = models.BinaryField(null=True, blank = True)
num_stars = models.IntegerField(default=0, blank = True)
class Lyrics(models.Model):
artist = models.ForeignKey(Artist)
title = models.CharField(max_length=100)
lyrics_content = models.TextField(null = False, blank=True)
comment = models.TextField(null=True, blank=True)
num_stars = models.IntegerField(default=0, blank = True)
song_language = models.CharField(max_length=50, null = True, blank=True)
class Song(models.Model):
artist = models.ForeignKey(Artist)
album = models.ForeignKey(Album)
name = models.CharField(max_length=100)
release_date = models.DateField(null = True, blank=True)
num_stars = models.IntegerField(default=0, blank=True)
song_file = models.TextField(null=True, blank=True)
class Album(models.Model):
artist = models.ManyToManyField(Artist)
name = models.CharField(max_length=100)
release_date = models.DateField(null = True, blank=True)
num_stars = models.IntegerField(default=0, blank=True)
At a quick glance, most things look OK.
In terms of the relationship between Song and Album, I would expect 1 song to be able to appear on more than one Album, so maybe a M2M relation there?
Also, songs could be performed by many Artists (original + several covers), so that relationship could probably be worked on in terms of flexibility, unless you want to treat a cover as a unique song - but then you get repetition of Lyrics, right?
Finally, I'm guessing the thumb field is to hold an image, so maybe that could be an ImageField?
Related
I'm trying to make auto field like that for invoice which is either part of customers table or invoice table it is okay in the 2 sitautions
the format I want like this Year-Month-auto depends on the number before it
for example : 202201-001 the first one , 202205-504 like that and it's auto generted once I create new customer
model.py
class customer(models.Model):
cust_id = models.BigAutoField(auto_created = True , primary_key=True, editable=False)
package = models.FloatField()
DOJ = models.DateField()
payment = models.IntegerField()
receipt = models.ForeignKey('receipt', on_delete=models.SET_NULL, null= True, blank=True)
balance = models.FloatField(null = True)
enq_id = models.ForeignKey('enquiry', on_delete=models.SET_NULL, null= True, blank=True)
lead_id = models.ForeignKey('lead', on_delete=models.SET_NULL, null= True, blank=True)
I'm trying to make full auto id for my invoices so I can use in my view
I have an app that allows users to signup and register for courses (from a 'TrainingInstance' model). These events have names etc and are categorised as Past or Current in the database (in the 'Training' model). When I show the BuildOrderForm in my template, I want only options for Current trainings to be shown in the dropdown menu. How can this be done in Django without javascript or Ajax?
I have the following form in forms.py:
class BuildOrderForm(forms.ModelForm):
class Meta:
model = Order
fields = ['training_registered']
And the following models in models.py:
class Training(models.Model):
""" Model which specifies the training category (name) and whether they are Past or Present"""
YEAR = (
('current', 'current'),
('past', 'past'),
)
name = models.CharField(max_length=200, null=True)
year= models.CharField(max_length=200, null=True, choices=YEAR, default='current')
def __str__(self):
return self.name
class TrainingInstance(models.Model):
""" Creates a model of different instances of each training ( May 2021 etc) """
name = models.CharField(max_length=200, null=True, blank=True)
venue = models.CharField(max_length=200, null=True, blank=True)
training = models.ForeignKey(Training, on_delete= models.CASCADE, null = True)
training_month = models.CharField(max_length=200, null=True, blank=True)
participant_date = models.CharField(max_length=20, null=True, blank=True)
staff_date = models.CharField(max_length=20, null=True, blank=True)
graduation_date = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return self.name
class Order(models.Model):
REGSTATUS = (
('registered', 'registered'),
('enrolled', 'enrolled'),
('holding', 'holding'),
('withdrawn', 'withdrawn'),
('waiting', 'waiting'),
)
customer = models.ForeignKey(Customer, on_delete= models.CASCADE, null = True)
training_registered = models.ForeignKey(TrainingInstance, on_delete= models.SET_NULL, blank = True, null = True)
registration_date = models.DateTimeField(null=True,blank=True)
regstatus = models.CharField(max_length=200, null=True, choices=REGSTATUS, default='registered')
def __str__(self):
return self.customer.username
Here is what I have done - which works but I'm also open to feedback about good/bad practice.
class BuildOrderForm(forms.ModelForm):
class Meta:
model = Order
fields = ['training_registered']
def __init__(self,*args,**kwargs):
super (BuildOrderForm,self ).__init__(*args,**kwargs)
self.fields['training_registered'].queryset = TrainingInstance.objects.filter(training__year ="current")
my models.py
class LiveClass_details(models.Model):
standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE)
chapter_details = models.TextField(default='')
mentor_id = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
doubtClass = models.OneToOneField(DoubtClasses, on_delete=models.PROTECT, null=True, blank=True)
isDraft = models.BooleanField(default=True)
ratings = models.FloatField(default=0)
no_of_students_registered = models.IntegerField(default=0)
# registered_students = models.ManyToManyField(RegisteredNames, null=True, blank=True)
no_of_students_attended = models.IntegerField(default=0)
class Meta:
verbose_name_plural = 'LiveClass_details'
class RegisteredNames(models.Model):
name = models.CharField(max_length=100, unique=True)
liveclass_id = models.ForeignKey
I am creating a endpoint where when a user register himself his name will get added to registered_students , so i had made a registered students ManyToMany Field hoping it will get updated when a user is registered but then i understand that it will contain all the names that are present in the RegisteredNames Model meaning names registered across all the liveclasses but i want only the names that are registered for a particular liveclass in the field so i need a array like field which i think is not possible so please help me in improving my logic, how can i achieve it
The documentation and django tutorials are very good: https://docs.djangoproject.com/en/3.2/topics/db/models/ https://docs.djangoproject.com/en/3.2/intro/tutorial02/#creating-models
Your code is very close. You don’t need the many-to-many field, and you need to specify the type of the Foreign key relationship in the RegisteredNames. You can do this:
class LiveClass_details(models.Model):
standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE)
chapter_details = models.TextField(default='')
mentor_id = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
doubtClass = models.OneToOneField(DoubtClasses, on_delete=models.PROTECT, null=True, blank=True)
isDraft = models.BooleanField(default=True)
ratings = models.FloatField(default=0)
no_of_students_attended = models.IntegerField(default=0)
class Meta:
verbose_name_plural = 'LiveClass_details'
class RegisteredNames(models.Model):
name = models.CharField(max_length=100, unique=True)
liveclass = models.ForeignKey(LiveClass_details, on_delete=Models.CASCADE)
Then, simply:
name = RegisteredNames.objects.create(name="Dhruv", liveclass_id=1)
To get all the registered names from a liveclass_details:
names = LiveClass_details.objects.get(id=1).registerednames_set.all()
num_reg = len(names)
I am trying to get the minimum or the lowest value of a model field in django model. The field is room_Price. I am therefore trying to get the minimum of value of this field for each instance of a model. My model are as as follows
class Hotels(models.Model):
name = models.CharField(max_length=255)
address = models.CharField(max_length=255)
city = models.CharField(max_length=255)
country = models.CharField(max_length=255)
mobile_number = models.CharField(max_length=12)
created_at = models.DateTimeField(default=timezone.now)
last_modified = models.DateTimeField(auto_now=True)
description = models.TextField()
slug = models.SlugField(unique=True)
property_photo = models.ImageField(default='default.jpg', upload_to='hotel_photos')
star_rating = models.PositiveIntegerField()
contact_person = models.ForeignKey(UserProfile, on_delete = models.CASCADE, null=True, blank=True,)
class Room(models.Model):
hotel = models.ForeignKey(Hotels,on_delete = models.CASCADE, null=True, blank=True,)
room_photo = models.ImageField(default='default.jpg', upload_to='room_photos')
room_Name = models.CharField(max_length = 200)
room_details = models.CharField(max_length = 500)
room_Capacity = models.PositiveIntegerField(default = 0)
slug = models.SlugField(unique=True)
# guest_numbers = models.IntegerField(default=0)
room_Price= models.PositiveIntegerField(default = 0)
total_Rooms = models.PositiveIntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, blank=True,)
More details
From the above models, a hotel can have as many rooms as possible. Now i want to fetch the lowest priced room for each hotel. I tried to use Hotels.objects.aggregate(min_price=Min('room__room_Price')) but it is fetching the overall minimum price of all the hotel rooms. Kindly assist
You can try to add ordering to your model and then find lowest price in a loop:
class Room(models.Model):
...
class Meta:
ordering = ['room_Price']
And filter in views:
lowest_prices = {}
for i in Hotels.objects.all():
price = Room.objects.filter(hotel=i.id)[0].room_Price
lowest_prices[i.name] = price
print(lowest_prices)
I put prices in a dict, but you can do anything you want with it.
I am creating a small app in Django where I need to maintain details of training batches of different courses. Each of these batches will have a list of topics to be covered. For e.g, A python course could be conducted by different trainers in different colleges at the same time and so they both will have their own list of topics. Following is what I have come up with but think I am wrong. I am confused about how to go about it. Kindly suggest the right approaches.
My Models so far,
class Course(models.Model):
name = models.CharField(max_length=50, default="Enter Course Name")
class Trainer(models.Model):
name = models.CharField(max_length=50, default="Enter Trainer Name")
class College(models.Model):
name = models.CharField(max_length=50, default="Enter College Name")
class CourseBatch(models.Model):
startDate = models.DateField(null = True, blank = True)
endDate = models.DateField(null = True, blank = True)
batchName = models.CharField(max_length=50, default="Enter Batch Name")
course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="course")
trainer = models.ForeignKey(Trainer, on_delete=models.CASCADE, related_name="trainer")
college = models.ForeignKey(College, on_delete=models.CASCADE, related_name="college")
class CheckPoints(models.Model):
description = models.CharField(max_length=50, default="Enter Description")
chkPoint = models.BooleanField(default=False)
course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="course")
class ChkListForBatch(models.Model):
batch = models.ForeignKey(CourseBatch, on_delete=models.CASCADE, related_name="coursebatch")
chkpoint = models.ForeignKey(CheckPoints, on_delete=models.CASCADE, related_name="chkpoint")
Here every CourseBatch needs to have its own set of CheckPoints (topics) to be covered. How can I implement the same?
As i understand it, you have a list of checkpoints to each cource. And you want to choose, which checkpoints will be for each particular batch.
Updated. If you want to save the completed control point or not, do this:
class Course(models.Model):
name = models.CharField(max_length=50, default="Enter Course Name")
class Trainer(models.Model):
name = models.CharField(max_length=50, default="Enter Trainer Name")
class College(models.Model):
name = models.CharField(max_length=50, default="Enter College Name")
class CourseBatch(models.Model):
startDate = models.DateField(null = True, blank = True)
endDate = models.DateField(null = True, blank = True)
batchName = models.CharField(max_length=50, default="Enter Batch Name")
course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="course")
trainer = models.ForeignKey(Trainer, on_delete=models.CASCADE, related_name="trainer")
college = models.ForeignKey(College, on_delete=models.CASCADE, related_name="college")
class CheckPoints(models.Model):
description = models.CharField(max_length=50, default="Enter Description")
course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="course")
class ChkListForBatch(models.Model):
batch = models.ForeignKey(CourseBatch, on_delete=models.CASCADE, related_name="coursebatch")
checkpoint = models.ForeignKey(CheckPoints, on_delete=models.CASCADE, related_name="chkpoint")
checkpoint_is_done = models.BooleanField(default=False)
class Course(models.Model):
name = models.CharField(max_length=50, default="Enter Course Name")
class Trainer(models.Model):
name = models.CharField(max_length=50, default="Enter Trainer Name")
class College(models.Model):
name = models.CharField(max_length=50, default="Enter College Name")
class CourseBatch(models.Model):
startDate = models.DateField(null = True, blank = True)
endDate = models.DateField(null = True, blank = True)
batchName = models.CharField(max_length=50, default="Enter Batch Name")
course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="course")
trainer = models.ForeignKey(Trainer, on_delete=models.CASCADE, related_name="trainer")
college = models.ForeignKey(College, on_delete=models.CASCADE, related_name="college")
class CheckPoints(models.Model):
description = models.CharField(max_length=50, default="Enter Description")
chkPoint = models.BooleanField(default=False)
course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="course")
course_batch = models.ForeignKey(to=CourseBatch, on_delete=models.CASCADE) # This means that you have multiple checkpoints associated with single coursebatch.
course_batch_m2m = models.ManyToManyField(to=CourseBatch) # This will create intermediate model, with columns checkpoints_id | coursebatch_id. This means multiple checkpoints has multiple coursebatch and vice-versa.
class ChkListForBatch(models.Model):
batch = models.ForeignKey(CourseBatch, on_delete=models.CASCADE, related_name="coursebatch")
chkpoint = models.ForeignKey(CheckPoints, on_delete=models.CASCADE, related_name="chkpoint")
Check CheckPoints model, I added ForeignKey and ManyToManyField with explanaitans.