Django Models, on delete set pk - python

This is my models:
class Customer(models.Model):
nome = models.CharField(max_length=40)
indirizzo = models.CharField(max_length=40)
class Appo(models.Model):
appo = models.CharField(max_length=40)
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True, default=1,related_name='appocli')
now, if I delete a Customer I need SQL set in Appo models a specific PK for customer Foreign Key. For example 1.
Something like: on delete set 1
Please help

You can use SET_DEFAULT to set your foreign key to a default value
customer = models.ForeignKey(Customer, on_delete=models.SET_DEFAULT, default=1)

Related

Automatic avoidance of category duplicates

I have the problem with Category Model.
I have 2 tables:
class Category(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=30, null=False)
class Movie(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=30, null=False)
so they are standard models with categories.
User can create Category by creating a movie with the name of category additionaly.
The problem is when user is trying to create Movie with category name that already exists, because it will create another category with the same name (like duplicate) and I want to avoid it.
How to do it?
I can't create unique name field, because many users can have same category (but I can use ManyToManyRelation) but still I don't know how to automatically avoid duplicates like bellow:
If Category with that Name and this User does not exist > create Category
If Category with that Name and this User exists > use this Category
Regards
Though your explanation is vague. But from your explanation, it seems like you want the categories to be unique with each user. Different users can have same categories, but same user can't have any duplicate one.
for that
class Category(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=30, null=False)
class Meta:
unique_together = ["user","name"] #This will
#make a constraint to check if both user and name is unique
According to your comment you want unique constraints with nullable ForeignKey too. try overriding the clean method in the model class (Category model)
from django.core.exceptions import ValidationError
def clean(self):
if self.user is None and Category.objects.filter(name=self.name, user=None).exists():
raise ValidationError("Duplicate Category with name=%s already exists" % self.name)
This will prevent the categories duplication. Just set unique to True.
class Category(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=30, unique=True)

Queryset foreign key models

I have two models below which one of the models inherits a foreign key from the model
class Services(models.Model):
name = models.CharField(max_length=200, null=True)
price = models.FloatField(null=True)
class Order(models.Model):
customer = models.ForeignKey(Customer, null=True, on_delete = models.SET_NULL)
service = models.ForeignKey(Service, null=True, on_delete = models.SET_NULL)
I want to get the value of the total value of orders per service (per instance)
So for example
if the id = 1 of service has made orders of £10, £33, etc. I would like to get the total value of that of that service based on how many orders it has been made.
So far I have made an queryset below
Order.objects.all().values_list('service__price')
Which provides me the list of prices, but I would like the total per instance of service.
How would one achieve this?
Your Question is wrong due to the wrong model design.
If you want to have a service but with different prices you need to put price on you order table.
Change your models to :
class Service(models.Model):
name = models.CharField(max_length=200, null=True)
class Order(models.Model):
customer = models.ForeignKey(Customer, null=True, on_delete = models.SET_NULL)
service = models.ForeignKey(Service, null=True, on_delete = models.SET_NULL, related_name='orders')
price = models.FloatField(null=True)
Then you can query your sum of prices for one service:
from django.db.models import Sum
s = Service.objects.get(id=1)
s.orders.all().aggregate(Sum("price"))

How to do many to one relationship in Django

I am doing a many to one relationship but I get a prompt that the field person in the report is without a default.
I tried setting the default to an empty space, I get an IntegrityError: NOT NULL constraint failed
class Person(models.Model):
person_name = models.CharField(max_length=255)
person_location = models.CharField(max_length=255, null=True)
classReport (models.Model):
person = models.ForeignKey(
Person, related_name='people', default="", on_delete=models.CASCADE)
product_name = models.CharField(max_length=255)
product_description = models.CharField(max_length=255)

Django ORM: Models with 2 table referencing each other

I have 2 tables. User and Group. 1:Many relationship. Each user can only belong to a single group.
here's the model.py.
class Group(models.Model):
group_name = models.CharField(max_length=150, blank=True, null=True)
group_description = models.TextField(blank=True, null=True)
group_creator = models.ForeignKey(User, models.DO_NOTHING)
class User(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
...
group = models.ForeignKey(Group, models.DO_NOTHING)
The issue I have is that they are both referencing each other which is acceptable in MySQL and Oracle, but, I get an error when migrating:
group_creator = models.ForeignKey(User, models.DO_NOTHING)
NameError: name 'User' is not defined
Now when I reverse the order (so, User first than Group), I get
group = models.ForeignKey(Group, models.DO_NOTHING, blank=True, null=True)
NameError: name 'Group' is not defined
This is getting quite frustrating. I have a few work around (make it a many:many and keep creator on Group class), but before I start destroying my datamodel and move data move all the data around, I wonder if anyone has this issue before. How did you solve this? Do you really have to change your datamodel?
as Pourfar mentioned in a comment, you may avoid the NameError via the quoting the model object as string. also it is safe to set related_name for accessing this relation.
class Group(models.Model):
...
group_creator = models.ForeignKey('User', related_name='creator_set')
and then, with your constraint,
Each user can only belong to a single group.
in that case, OneToOneField is more appropriate.
class User(models.Model):
...
group = models.OneToOneField(Group)
then you can access the relations as follows:
# USER is a User object
GROUP_BELONGED = USER.group # access to 1-1 relation
GROUP_CREATED = USER.creator_set.all() # reverse access to foreignkey relation
# now GROUP_BELONGED is a Group object
CREATOR = GROUP_BELONGED.group_creator # access to foreignkey relation
Add related_name to your ForeignKey fields:
class Group(models.Model):
group_name = models.CharField(max_length=150, blank=True, null=True)
group_description = models.TextField(blank=True, null=True)
group_creator = models.ForeignKey('User',related_name='myUser')
class User(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
group = models.ForeignKey('Group', related_name='MyGroup')

Django ManyToMany field is not created in model

Here is my Model for Teacher class.
class Teacher(Profile):
class Meta:
db_table = 'teacher'
user = models.OneToOneField(User,
unique=True,
verbose_name=_('user'),
related_name='teacher')
home_address = models.CharField(_('home_address'), max_length=255, blank=True)
home_phone = models.CharField(_('home_phone'), max_length=30, blank=True)
cell_phone = models.CharField(_('cell_phone'), max_length=30, blank=True)
experience = models.IntegerField(default = 0)
summary = models.TextField(_('summary'), max_length=500, blank=True)
subjects = models.ManyToManyField(Subjects, through='SubjectsIntermediate')
When i execute the manage.py syncdb it does creates the teacher table with all fields except for field subjects. Why the subjects field is not created??
Because a ManyToMany isn't a field, at least not one that exists as a database column. It's a relationship with a linking table. You'll find that a table named myapp_teacher_subjects has been created, with foreign keys to both teacher and subjects.

Categories