I a trying to generate a primary key using the other fields of the model.
unique_id = models.CharField(max_length=10, primary_key=True)
restaurant_name = models.CharField(max_length=100)
manager_name = models.CharField(max_length=50)
email = models.EmailField(max_length=100, unique=True)
mobile_no = models.CharField(unique=True, validators=[validate_mobile], max_length=10)
state = models.CharField(choices=STATES, max_length=2)
city = models.CharField(max_length=20)
pincode = models.CharField(max_length=8, validators=[validate_pincode])
street_address = models.CharField(max_length=100)
password = models.CharField(max_length=256)
You can make use of the default field option.
See: https://docs.djangoproject.com/en/2.0/ref/models/fields/#default
Just like how it's done on UUIDField.
See: https://docs.djangoproject.com/en/2.0/ref/models/fields/#uuidfield
Then I'm guessing just try to assign your algo each and every time on your unique_id
Related
I have specified that my bio and image fields can be empty, but why does it give me an error and say that I have to fill it in?
class User_account(models.Model):
email = models.EmailField()
fullname = models.CharField(max_length=30)
username = models.CharField(max_length=20)
password = models.CharField(max_length=30)
marital_status = models.BooleanField(default=False)
bio = models.CharField(null=True, max_length=200)
visitor = models.IntegerField(default=0)
image = models.ImageField(null=True, upload_to='profile_img')
Specifying null=True [Django-doc] does not mean the field is not required. null=True has only impact on the database: it makes the field NULLable. You should use blank=True [Django-doc] to make the field not required:
class User_account(models.Model):
# …
bio = models.CharField(null=True, blank=True, max_length=200)
# …
image = models.ImageField(null=True, blank=True,
Note: Models in Django are written in PascalCase, not snake_case,
so you might want to rename the model from User_account to UserAccount.
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 have existing model which was created before, and I would like to add ForeignKey property to User model, when I run migrations command, I take following errors (the full trace in images):
The model:
class Patient(models.Model):
number = models.IntegerField()
last_name = models.CharField(max_length=30)
first_name = models.CharField(max_length=30)
middle_name = models.CharField(max_length=30)
birthday = models.DateField(default=datetime.date.today)
age = models.IntegerField(null=True)
fromdate = models.DateField(default=datetime.date.today)
appdate = models.DateField(default=datetime.date.today)
district = models.ForeignKey(District, on_delete = models.CASCADE)
address = models.TextField(default='')
gender = models.BooleanField(default=True)
occupation = models.ForeignKey(Occupation, on_delete = models.CASCADE)
# it is extra field for patient to prevent from deleting them
status = models.BooleanField(default=True)
author = models.ForeignKey(
User,
on_delete=models.CASCADE,
)
In addition, in an another project, I have done the same action without facing any difficulties.
My aim is to retrieve data from different model with the reference of entity type & entity id.
Example:
I have Customer model & Address model
from django.db import models
class Customer(models.Model):
name = models.CharField(null=False, blank=False, max_length=255)
email = models.EmailField(null=False, blank=False, unique=True)
class Address(models.Model):
entity_type = models.CharField(null=False, max_length=255)
entity_id = models.PositiveIntegerField(null=False)
address1 = models.CharField(max_length=255)
address2 = models.CharField(max_length=255)
for now i using raw query
cursor.execute("SELECT * FROM customers AS cust
INNER JOIN addresses AS addrs ON
(cust.id = addrs.entity_id AND 'customer' = addrs.entity_type)
WHERE cust.id IN (%s)", [ids])
But this is not Good solution. Take too much time when ids is in thousands of range.
If is there any other way to archive those data. Then please give your solution in comments..
It seems awkward to manage an ID to an external entity with an "entity_id" field. Why not use a ForeignKey field to a Customer, or in case the entity is not always a Customer, use a GenericForeignKey ?
Right now you are reinventing the wheel.
class Address(models.Model):
entity_type = models.CharField(null=False, max_length=255)
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL)
Then:
q = Address.objects.filter(customer in cutomers_collection)
The doc about ForeignKey: https://docs.djangoproject.com/en/3.0/ref/models/fields/#django.db.models.ForeignKey
query_set = Address.objects.filter(
Q(entity_type='R') | Q(entity_id=1)
)
from django.db import models
class Customer(models.Model):
name = models.CharField(null=False, blank=False, max_length=255)
email = models.EmailField(null=False, blank=False, unique=True)
class Address(models.Model):
entity_type = models.CharField(null=False, max_length=255)
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL)
address1 = models.CharField(max_length=255)
address2 = models.CharField(max_length=255)
data = Address.objects.filter(entity_type='customer', customer_id__in=[ids]).values('address1', 'address2', 'customer__name', 'customer__email')
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>