How to add ArrayField in Django? - django

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)

Related

How to use django-autocomplete-light and django-hacker to make a chained dropdown in django admin?

I have 3 models 1) university 2) courses and 3) enquiry.
My enquiry model has a foreign key to "course". And Course has a foreign key to the university. I only want to show the courses related to that university while adding an enquiry. I tried django-smart-select but failed to do so. I tried This answer but I dont understand the logic and failed to implement in my project.
this is my models.py file
class university(models.Model):
univ_name = models.CharField(max_length=100)
country = CountryField(blank=True, null=True)
univ_desc = models.CharField(max_length=1000)
univ_logo = models.ImageField(upload_to="media")
univ_phone = models.CharField(max_length=10, blank=True)
univ_email = models.EmailField(max_length=254, blank=True)
univ_website = models.URLField(blank=True)
assigned_users = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, default="")
def __str__(self):
return self.univ_name
class Meta:
verbose_name_plural = "Universities"
class Course(models.Model):
university = models.ForeignKey(university, on_delete=models.CASCADE)
course_name = models.CharField(max_length=100)
course_levels = models.ForeignKey(course_levels, on_delete=models.CASCADE)
intake = models.ForeignKey(intake, on_delete=models.CASCADE)
documents_required = models.ForeignKey(documents_required, on_delete=models.CASCADE)
course_requirements = models.ForeignKey(course_requirements, on_delete=models.CASCADE)
Active = models.BooleanField()
def __str__(self):
return self.course_name
class enquiry(models.Model):
student_name = models.CharField(max_length=100)
student_phone = models.CharField(max_length=10)
student_email = models.EmailField()
student_address = models.TextField()
current_education = models.ForeignKey(current_education, on_delete=models.CASCADE)
country_interested = CountryField(blank=True, null=True)
university_interested = models.ForeignKey(university, on_delete=models.CASCADE)
course_interested = models.ForeignKey(Course, on_delete=models.CASCADE, limit_choices_to={'Active':True})
level_applying_for = models.ForeignKey(course_levels, on_delete=models.CASCADE)
intake_interested = models.ForeignKey(intake, on_delete=models.CASCADE)
assigned_users = models.ForeignKey(User, on_delete=models.CASCADE, default="", limit_choices_to={"is_active": True})
enquiry_status = models.ForeignKey(enquiry_status, on_delete=models.CASCADE, default="")
course_interested= ChainedForeignKey(Course,chained_field= 'university_interested',chained_model_field= 'university',show_all= False,auto_choose= True,sort=True,limit_choices_to = {"Active": True},)
I want to show the course_interested field related to that university. Need help.
I tried using django-smart-select but failed to implement it. I am not aware of jquery and ajax so that is out of the question to use in my project.
got the solution I used the django-select2 and was able to solve this issue.

How to create a relationship on the field of a model with three different models in django?

Just a fool question I have a model Exam which contains a field Subject which I want to connect with 3 or 4 or even 5 subjects like foreign key connect one with it.
# 1 type
class Math(models.Model):
id = models.CharField(primary_key=True, max_length=200, blank=True)
chapter = models.ForeignKey(Chapters, on_delete=models.CASCADE)
name = models.CharField(max_length=250)
marks_contain = models.IntegerField(default=10)
question = RichTextUploadingField()
hint = RichTextUploadingField()
created_at = models.DateTimeField(auto_now_add=True, blank=True)
# 2 type
class Science(models.Model):
id = models.CharField(primary_key=True, max_length=200, blank=True)
chapter = models.ForeignKey(Chapters, on_delete=models.CASCADE)
name = models.CharField(max_length=250)
marks_contain = models.IntegerField(default=10)
question = RichTextUploadingField()
hint = RichTextUploadingField()
created_at = models.DateTimeField(auto_now_add=True, blank=True)
# 3 type
class Computer(models.Model):
id = models.CharField(primary_key=True, max_length=200, blank=True)
chapter = models.ForeignKey(Chapters, on_delete=models.CASCADE)
name = models.CharField(max_length=250)
marks_contain = models.IntegerField(default=10)
question = RichTextUploadingField()
hint = RichTextUploadingField()
created_at = models.DateTimeField(auto_now_add=True, blank=True)
class Exam(models.Model):
id = models.AutoField(primary_key=True)
created_at = models.DateTimeField(auto_now_add=True, blank=True)
name = models.CharField(max_length=255)
subject = models.ForeignKey([object.Math or object.Science or object.Computer]) # I want to do something like this
I know this is not possible with foreign-key but what is the way to do things like this?
It's possible with ManyToMany, but you have to create new model:
from django.utils.module_loading import import_string
class Subject(models.Model):
class_name = models.CharField(...)
def get_class(self):
return import_string(f"app_name.models.{self.class_name}")
class Exam(...):
...
subject = models.ManyToManyField(Subject, default=None, blank=True)
Then simply create Subject object for each model you want to be with class_name exactly as you have your subject __class__ name, i.e. Subject.objects.create(class_name="Math"). Then replace app_name with name of your app that models.py is inside.
If you need real class from Subject class just call subject.get_class(), and you will get object: <class 'app_name.models.Math'>.

How i can change my query to work in django?

I want to make a request from two tables at once, I registered dependencies in the class. But the request does not work for me. What is wrong with him?
views.py
def payments(request):
paymentsss = Transaction.objects.select_related("currency_id")[:5]
return render(request, "payments.html", {"paymentsss": paymentsss})
models.py
class Transaction(models.Model):
id = models.BigIntegerField(blank=True, null=False, primary_key=True)
currency_id = models.ForeignKey(Currency, null=True, on_delete=models.CASCADE)
deal_id = models.ForeignKey(Deal, null=True, related_name='deal', on_delete=models.CASCADE)
service_instance_id = models.ForeignKey(ServiceInstance, null=True, related_name='service_instance', on_delete=models.CASCADE)
payment_source_id = models.ForeignKey(PayerPaymentSource, null=True, related_name='payment_source', on_delete=models.CASCADE)
payment_date = models.DateTimeField(blank=True, null=True)
amount = models.IntegerField(blank=True, null=True)
status = models.CharField(max_length=255, blank=True, null=True)
context = models.TextField(blank=True, null=True) # This field type is a guess.
class Meta:
managed = False
db_table = '"processing"."transaction"'`enter code here`
And Currency for example:
class Currency(models.Model):
id = models.SmallIntegerField(blank=True, null=False, primary_key=True)
name = models.CharField(max_length=128, blank=True, null=True)
iso_name = models.CharField(max_length=3, blank=True, null=True)
minor_unit = models.SmallIntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = '"processing"."currency"'
My Error:
I would be glad if there is an example of how to make a larger request. From 3-4 tables.
Change the db_table
class Meta:
managed = False
db_table = 'processing.transaction'
class Meta:
managed = False
db_table = 'processing.currency'
You need to change the column names for the foreign keys: e.g. currency = ForeignKey(...) and deal = ForeignKey(...).
The field is a reference to the object itself, not to the id of the object. You can see that behind the scenes, Django queries using currency_id_id which doesn't make sense.
If your column name is currency_id (in your database), then your field name should be currency.

Changing django default pk with AutoField to BigAutoField

My model has a default pk with AutoField (integer) but later on i discovered that i need to use BigAutoField instead!
And also i have data in then with other models referencing the student model:: how do i change the pk field to BigAutoField and also reflects on other referencing models
class Student(models.Model):
matric_no = models.CharField(max_length=20, unique=True) # first set it to U(random)
password = models.CharField(max_length=128)
session = models.ForeignKey(Session, null=True)
programme = models.ForeignKey(Programme, null=True)
school = models.ForeignKey(School, null=True)
course_comb = models.ForeignKey(CourseComb, null=True)
serial = models.IntegerField(null=True)
current_level = models.CharField(max_length=3, choices=LEVEL_CHOICES, default='100', null=True)
last_login = models.DateField(null=True)
is_active = models.CharField(max_length=1, default=1, choices=((1, 1), (0, 0)))
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(auto_now=True)
a model referencing Student
class Profile(models.Model):
student = models.OneToOneField(Student, on_delete=models.CASCADE)
attachment = models.ImageField(null=True, blank=True, verbose_name="Profile Image")
surname = models.CharField(max_length=255, null=True, verbose_name="Surname")
othernames = models.CharField(max_length=255, null=True, verbose_name="Othernames")
SEX_CHOICES = (
("M", "Male"),
("F", "Female")
)
Set primary_key=True in the field definition:
id = models.BigAutoField(primary_key=True)
If you want to use this in multiple models you could also make an abstract model and let others inherit it:
class BigPkAbstract(models.Model):
id = models.BigAutoField(primary_key=True)
class Meta:
abstract = True
And in your other models:
class SomeModel(BigPkAbstract):
<your model here>
‌

Django 2.1 ProgrammingError at /admin column + _id does not exist

While trying to run my second Django 2.1 /Postgres 10 project I got stuck with the following programming error:
ProgrammingError at /admin/vocs_app/subsubscriber/
column sub_subscriber.sub_prev_sst_uid_id does not exist
LINE 1: ...", "sub_subscriber"."sub_next_recharge_datetime", "sub_subsc...
^
HINT: Perhaps you meant to reference the column "sub_subscriber.sub_prev_sst_uid".
I can open the admin app of my application, i.e., 127.0.0.1:8000/admin/vocs_app.
It lists all imported models from my database; to illustrate my case I believe the following classes are sufficient:
(taken from my_site/vocs_app/models.py:)
from django.db import models
class VneVirtualNetwork(models.Model):
vne_uid = models.BigAutoField(primary_key=True)
vne_nop_uid = models.ForeignKey(NopNetworkOperator, models.DO_NOTHING, db_column='vne_nop_uid')
vne_name = models.CharField(max_length=50)
vne_code = models.CharField(max_length=50)
vne_external_id = models.CharField(max_length=100, blank=True, null=True)
vne_idd_code = models.CharField(max_length=5)
vne_sn_length = models.IntegerField()
createdon = models.DateTimeField()
createdby = models.CharField(max_length=150)
createdfrom = models.CharField(max_length=150)
modifiedon = models.DateTimeField()
modifiedby = models.CharField(max_length=150)
modifiedfrom = models.CharField(max_length=150)
class Meta:
managed = False
db_table = 'vne_virtual_network'
class SstSystemStatus(models.Model):
sst_uid = models.BigAutoField(primary_key=True)
sst_name = models.CharField(max_length=50)
sst_description = models.CharField(max_length=100, blank=True, null=True)
startdate = models.DateField(blank=True, null=True)
enddate = models.DateField(blank=True, null=True)
class Meta:
managed = False
db_table = 'sst_system_status'
class SubSubscriber(models.Model):
sub_uid = models.BigAutoField(primary_key=True)
sub_vne_uid = models.ForeignKey('VneVirtualNetwork', models.DO_NOTHING, db_column='sub_vne_uid')
sub_rpl_uid = models.ForeignKey(RplRatePlan, models.DO_NOTHING, db_column='sub_rpl_uid')
sub_account_user_id = models.CharField(max_length=100, blank=True, null=True)
sub_external_id = models.CharField(max_length=100)
sub_hzn_uid = models.ForeignKey(HznHomezoneName, models.DO_NOTHING, db_column='sub_hzn_uid')
sub_low_balance_trigger = models.BooleanField()
sub_first_call_datetime = models.DateTimeField(blank=True, null=True)
sub_last_enabled_datetime = models.DateTimeField(blank=True, null=True)
sub_last_disabled_datetime = models.DateTimeField(blank=True, null=True)
sub_last_recharge_datetime = models.DateTimeField(blank=True, null=True)
sub_next_recharge_datetime = models.DateTimeField(blank=True, null=True)
sub_prev_sst_uid = models.ForeignKey(SstSystemStatus, related_name='sub_prev_sst_uid',on_delete=models.DO_NOTHING)
sub_sst_uid = models.ForeignKey(SstSystemStatus, related_name='sub_sst_uid',on_delete=models.DO_NOTHING)
startdatetime = models.DateTimeField()
enddatetime = models.DateTimeField()
createdon = models.DateTimeField()
createdby = models.CharField(max_length=150)
createdfrom = models.CharField(max_length=150)
modifiedon = models.DateTimeField()
modifiedby = models.CharField(max_length=150)
modifiedfrom = models.CharField(max_length=150)
class Meta:
managed = False
db_table = 'sub_subscriber'
class SubSubscriber references foreign key sst_uid of table/class SstSystemStatus twice (previous and current status). It seems Django doesn't like it. Other tables such as VneVirtualNetwork (which contain a "single" foreign key references) don't cause any issue. The admin GUI allows me to display and change their data.
The fault message shows that Django tries to complement the name of field sub_prev_sst_uid with '_id'. If I comment the relevant line in file model.py and try to display the subscriber table it will cause the same error, this time with field sub_sst_uid. How can I prevent Django from appending '_id'?
Thanks in advance for any advice.
By default, Django will use the related name and/or the chosen class field name, add a suffix "_id" and try to locate a column of this name in the database. Unless you explicitly define the db_column as follows:
sub_sst_uid = models.ForeignKey('SstSystemStatus', db_column='sub_sst_uid', related_name='sub_sst_uid', on_delete=models.DO_NOTHING)
sub_prev_sst_uid = models.ForeignKey('SstSystemStatus', db_column='sub_prev_sst_uid', related_name='sub_prev_sst_uid', on_delete=models.DO_NOTHING)