I have a ForeignKey field in my model and in Django admin and Django forms` when I display that field or in Django admin, I get all the field that in that model However, I only want to display selected fields in that dropdown, for example
class Area(models.Model):
area_type_options = (('cc', 'Cost Center'), ('pc', 'Profit Center'),)
name = models.CharField(max_length=100)
area_type = models.CharField(max_length=100, choices=area_type_options)
class Item(models.Model):
name = models.CharField(max_length=150, null=True, unique=True)
profit_center = models.ForeignKey(Area, null=True, blank=True, on_delete=models.CASCADE, related_name='profit_center')
cost_center = models.ForeignKey(Area, null=True, blank=True, on_delete=models.CASCADE, related_name='cost_center')
I get to see all the records in the cost_center and all the records in the profit_center however I only want to see where area_type is cc to cost_center and where area type pc to profit_center
Please Help
You can use ForeignKey.limit_choices_to [Django docs] to do this:
class Item(models.Model):
name = models.CharField(max_length=150, null=True, unique=True)
profit_center = models.ForeignKey(Area, null=True, blank=True, on_delete=models.CASCADE, related_name='profit_center', limit_choices_to={'area_type': 'pc'})
cost_center = models.ForeignKey(Area, null=True, blank=True, on_delete=models.CASCADE, related_name='cost_center', limit_choices_to={'area_type': 'cc')
Related
I want to check whether the current user already has the same movie id in his personal list or not. If he has it then I want to exclude that movie from my trending list.
I want it to be something like this.
views.py
trending = list(Movies.objects.exclude(mid in mymovies WHERE uid = request.user.id))
models.py
class Movies(models.Model):
mid = models.CharField(max_length=255, primary_key=True)
title = models.CharField(max_length=255, null=True, blank=True)
rating = models.CharField(max_length=5, null=True, blank=True)
type = models.CharField(max_length=255, null=True, blank=True)
genre = models.CharField(max_length=255, null=True, blank=True)
rdate = models.CharField(max_length=255, null=True, blank=True)
language = models.CharField(max_length=255, null=True, blank=True)
cover = models.CharField(max_length=255, null=True, blank=True)
description = models.TextField(null=True, blank=True)
sequal = models.CharField(max_length=255, null=True, blank=True)
trailer = models.CharField(max_length=255, null=True, blank=True)
year = models.CharField(max_length=5, null=True, blank=True)
objects = models.Manager()
def __str__(self) -> str:
return self.title
class MyMovies(models.Model):
mid = models.ForeignKey(Movies, on_delete=CASCADE)
uid = models.ForeignKey(User, on_delete=CASCADE, null=True, blank=True)
watched = models.BooleanField()
date = models.DateTimeField(auto_now_add=True)
objects = models.Manager()
You can .exclude(…) with:
trending = Movies.objects.exclude(mymovies__uid=request.user)
If you specified a related_query_name=… [Django-doc] or a related_name=… [Django-doc], then you need to use that to make a JOIN with your Movies model:
trending = Movies.objects.exclude(related_name_of_fk__uid=request.user)
Note: normally a Django model is given a singular name, so MyMovie instead of MyMovies.
Note: Normally one does not add a suffix _id to a ForeignKey field, since Django
will automatically add a "twin" field with an _id suffix. Therefore it should
be user, instead of uid.
I have a Django model "Inspection" which has:
InspectionID (PK)
PartID
SiteID
Date
Comment
Report
Signiture
I want to be able to have a one to many relationship between the inspection ID and date. So one ID can have inspections at many dates. How would I do this? I currently have the following:
class Inspection(models.Model):
InspectionID = models.IntegerField(primary_key=True, unique=True)
PartID = models.ForeignKey('Part', on_delete=models.CASCADE)
SiteID = models.ForeignKey('Site', on_delete=models.CASCADE)
Date = models.DateField(auto_now=False, auto_now_add=False)
Comment = models.CharField(max_length=255, blank=True)
Report = models.FileField(upload_to='docs', null=True, blank=True)
Signiture = models.CharField(max_length=255, blank=True)
I thought about using models.ForeignKey but I really don't know how to implement that properly in this situation.
I want to be able to have a one to many relationship between the inspection ID and date.
You create an extra model, like:
class InspectionDate(models.Model):
inspection = models.ForeignKey(
Inspection,
on_delete=models.CASCADE,
related_name='inspectiondates'
)
date = models.DateField()
You thus can create InspectionDates for a given Inspection.
Or if you want to add extra data, it might be better to define an InspectionGroup model:
class InspectionGroup(models.Model):
pass
class Inspection(models.Model):
id = models.AutoField(primary_key=True, unique=True, db_column='InspectionId')
inspectiongroup = models.ForeignKey(InspectionGroup, on_delete=models.CASCADE, db_column='InspectionGroupId')
part = models.ForeignKey('Part', on_delete=models.CASCADE, db_column='PartId')
site = models.ForeignKey('Site', on_delete=models.CASCADE, db_column='SiteId')
date = models.DateField(db_column='Date')
comment = models.CharField(max_length=255, blank=True, db_column='CommentId')
report = models.FileField(upload_to='docs', null=True, blank=True, db_column='ReportId')
signiture = models.CharField(max_length=255, blank=True, db_column='Signature')
Note: the name of attributes are normally written in snake_case [wiki], not in PerlCase or camelCase.
you may store 'self Foriegnkey' as
class Inspection(models.Model):
InspectionID = models.IntegerField(primary_key=True, unique=True)
PartID = models.ForeignKey('Part', on_delete=models.CASCADE)
SiteID = models.ForeignKey('Site', on_delete=models.CASCADE)
Date = models.DateField(auto_now=False, auto_now_add=False)
Comment = models.CharField(max_length=255, blank=True)
Report = models.FileField(upload_to='docs', null=True, blank=True)
Signiture = models.CharField(max_length=255, blank=True)
inspection_id = models.ForeignKey('self', null=True, blank=True)
I have created a role model for Employee so that employee will be assigned to control
the overall app based on his/her role. I mean if the role of employee is given can_create_only, then the employee should be able to create inventory, orders, items etc and if employee is given can_create_edit_and_delete, then the employee would be like one of the admin and etc. For this I have designed the model as below but I want to know what is the best way to handle such and why?
Should I go with middleware or decorator way? Can anyone give me an example, please?
class Role(models.Model):
name = models.CharField(max_length=100, blank=False, null=False)
class Meta:
verbose_name = 'Role'
verbose_name_plural = 'Roles'
class Employee(models.Model):
office = models.ForeignKey(
OfficeSetup, blank=False, null=False, on_delete=models.CASCADE)
name = models.CharField(max_length=150, blank=False, null=False)
designation = models.ForeignKey(Designation, blank=False, null=False)
section = models.ForeignKey(DepartmentSetup, blank=True, null=True)
phone_number = models.CharField(max_length=150, blank=True, null=True)
mobile_number = models.CharField(max_length=150, blank=True, null=True)
email = models.EmailField(max_length=150, blank=False, null=False)
gender = models.CharField(
max_length=4, choices=GENDER, blank=True, null=True)
role = models.ForeignKey(Role, blank=True, null=True)
username = models.CharField(max_length=100, blank=False, null=False)
password = models.CharField(max_length=100, blank=False, null=False)
avatar = models.ImageField(
null=True, blank=True, upload_to=upload_employee_image_path)
class Meta:
verbose_name = 'Employee'
verbose_name_plural = 'Employees'
def __str__(self):
return self.name
When creating an employee by admin, the username, password and email, the admin provides will create a new user instance along with the employee
Django comes with Groups and permissions which provides all most everything you are looking for.
This may help you - How do I use Django groups and permissions?
Django documentation - https://docs.djangoproject.com/en/1.11/topics/auth/
In database I have already registered 4 persons but they were registered when model hasn't had relation attributes yet. When I added them I got this model:
class Person(User):
type = models.BooleanField()
avatar = models.ImageField(blank=True)
second_name = models.CharField(max_length=30, blank=True, default='')
birthday = models.DateField(blank=True, default=None)
country = models.CharField(max_length=30, blank=True, default='')
city = models.CharField(max_length=30, blank=True, default='')
school = models.CharField(max_length=60, blank=True, default='')
university = models.CharField(max_length=60, blank=True, default='')
work_place = models.CharField(max_length=60, blank=True, default='')
profession = models.CharField(max_length=60, blank=True, default='')
phone = models.CharField(max_length=30, blank=True, default='')
about = models.TextField(blank=True, default='')
latitude = models.FloatField(blank=True, default=-1)
longitude = models.FloatField(blank=True, default=-1)
friends = models.ForeignKey(
'self',
related_name='+',
)
black_list = models.ForeignKey(
'self',
related_name='+',
)
dialogues = models.ManyToManyField(
'dialogues.Dialogue',
)
news = models.OneToOneField(
'news.NewsList',
)
wall = models.OneToOneField(
'blogs.Blog',
)
But now when this model migrates I have the error: django.db.utils.IntegrityError: UNIQUE constraint failed: persons_person.wall_id.
You should change the relation with Blog model, as one Person can write more than 1 blog, hence its a 1-M relation. So in Blog model you should define a ForeignKey to Person model.
person = models.ForeignKey(
'person.Person',
related_name='walls'
)
And wall field will be removed from Person model, but from person objects you will be able to access blogs using related name walls.
If your have a necessity of having Person to Blog as 1-1 relation, then your will have to remove records from database which don't follow this constraint.
I have following two models
class Questionnaire(models.model)
name = models.CharField(max_length=128, null=True, blank=True)
type = models.CharField(max_length=128,choices=questionnaire_choices)
class TestPopulation(models.Model)
user = models.ForeignKey(User, blank=True, null=True)
age = models.CharField(max_length=20, blank=True, null=True)
education = models.CharField(max_length=50, blank=True, null=True,
choices=EDUCATION_CHOICES)
questionnaire = models.ManyToManyField(Questionnaire, blank=True, null=True)
Now how can i get number of questionnaires for the specific user (logged in user). ?
test_population = TestPopulation.objects.get(user=user)
test_population.questionnaire.all()
questionnaire.objects.filter(test_population__user=user).count()