Django UNIQUE constraint failed with OneToOneField while migrate in Django User Model - python

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.

Related

Django many to many filter

I have many to many field in user model where one user can have multiple roles for example admin, patient, doctor and others. now I want to query data to get users with admin and all other roles and not doctor and patient role. I am using this
User.objects.exclude(roles__code_name__in=['pt', 'doc'])
now my one user signs up as patient too so he has admin and patient role both now i am unable to get him by using above query. so concluding... if user has two roles if one of it is patient and he has any other role too i want to get him too. what should i do? Thanks in advance
UPDATE
class User(AbstractBaseUser):
username = models.CharField(max_length=30, unique=True)
email = models.EmailField(max_length=60, blank=True, null=True)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
cnic = models.CharField(max_length=13, unique=True)
mobile = models.CharField(max_length=11, unique=True)
dob = models.DateField(blank=True, null=True)
full_name = models.CharField(max_length=90, blank=True, null=True)
profile_image = models.ImageField(max_length=255, upload_to=get_profile_image_path, null=True, blank=True, default=get_default_profile_image_path)
next_of_kin_name = models.CharField(max_length=60, blank=True, null=True)
next_of_kin_mobile = models.CharField(max_length=11, blank=True, null=True)
is_delete = models.BooleanField(default=False)
status = models.IntegerField(default=0)
contact = models.CharField(max_length=10, blank=True, null=True)
hospital = models.ForeignKey('Hospital', on_delete=models.SET_NULL, blank=True, null=True)
roles = models.ManyToManyField('Role', related_name='users')
is_staff = models.BooleanField(default=False)
balance = models.PositiveIntegerField(default=0)
gender = models.CharField(max_length=10, choices=gender_choices, default=gender_choices[0][0])
phone_verified = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey('self', related_name='+', blank=True, null=True, on_delete=models.CASCADE)
updated_at = models.DateTimeField(auto_now=True)
updated_by = models.ForeignKey('self', related_name='+', blank=True, null=True, on_delete=models.CASCADE)
This is my model it has roles as many to many field. i have multiple roles like doctor, patient, admin and many others custom created roles with custom permissions. I have a view where i want to get data of users that are not patients or doctors. everything was working fine until one of my admin user decides to sign up as patient so he has now both patient and admin role and now i am unable to get him by using above mentioned query
Eureka. This solution is working fine for me idk if it's the ideal approach bit is working at the moment. Thanks #all
User.objects.annotate(num_roles=Count('roles')).exclude(Q(id=self.request.user.id) | Q(is_delete=True) | Q(roles__code_name__in=['pt', 'doc', 'su']) & Q(num_roles=1)).order_by('-id')

Two dependent conditions in exclude DJANGO

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.

django ForeignKey field should only select by category

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')

create custom role in django to employees

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/

Django query for many to many relationship

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()

Categories