Is it possible get two fields from parent model to one child model using foreign key? - python-3.x

consider the below models,
class Country_City(models.Model):
country_name = models.CharField(max_length=200)
city_name = models.CharField(max_length=200)
class Register_user(models.Model):
country = models.ForeignKey(Country, on_delete=models.CASCADE,related_name='country', null=True)
city = models.ForeignKey(Country_City,on_delete=models.CASCADE,related_name='city',null=True)
is it a right way to use?
I want to get two fields from parent model to child model

That's simple you can access all fields from parent table to the child table and child to parent. Django gives you foreign key feature and reverse relationship as well.
class Country_City(models.Model):
country_name = models.CharField(max_length=200)
city_name = models.CharField(max_length=200)
class Register_user(models.Model):
name = models.CharField(max_length=50)
city = models.ForeignKey(Country_City,on_delete=models.CASCADE,related_name='city',null=True)
You can make models like this and if you want to access any fields from child to parent then you can use foreign key to access any fields from parent table and reverse as well.

Related

django-modeltranslate default language duplicate value

My model:
class DoctorSpeciality(BaseModel):
name = models.CharField(max_length=255, unique=True, db_index=True)
class Meta:
db_table = 'doctor_specialities'
When I am trying to translate this model, Django Modeltranslation creates two fields name_de, and name_en. But I also have the name field, name and name_de have the same value. Is it possible not to create a default language column in the database to prevent duplicated values?

In Django, how to create a model that stores proposed changes to another model?

I'm using Python 3.9 and Django 3.2. I have the following model
class Coop(models.Model):
objects = CoopManager()
name = models.CharField(max_length=250, null=False)
types = models.ManyToManyField(CoopType, blank=False)
addresses = models.ManyToManyField(Address, through='CoopAddressTags')
enabled = models.BooleanField(default=True, null=False)
phone = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_phone')
email = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_email')
web_site = models.TextField()
description = models.TextField(null=True)
approved = models.BooleanField(default=False, null=True)
We would like to set up a situation where someone could propose a change to a row in the db that would be reviewed before being saved, so I've created this struture
class CoopChange(Coop):
"""
"""
created_at = models.DateTimeField(null=False, default=datetime.now)
The problem is that when I create a migration, the table that is created simply points back to the original model, instead of storing all the fields
Table "public.directory_coopchange"
Column | Type | Modifiers
-------------+--------------------------+-----------
coop_ptr_id | integer | not null
created_at | timestamp with time zone | not null
This is non-ideal because the original table would contain both finalized entries and those suggested for changes. Is there a way to create an entity that stores proposed changes that mirrors the structure of the original entity?
There are a few of ways you could tackle this
Change Coop to an abstract base class:
https://docs.djangoproject.com/en/4.0/topics/db/models/#abstract-base-classes
Then you can inherit two classes from it CoopProposed and CoopApplied and you can work out what logic happens to create each
Just use the one class Coop and add a property called approved defaulted to False and then set it to True when you approve the changes.
This might not be what you want as it will overwrite any previous changes and you might want to keep a history of changes.
Add a property proposed as a JSONField (check the docs if the DB you are using supports it) on the Coop class. This can store a whole dictionary with the keys and values of the proposed changes. When approved, the field can be read and applied to the model's properties in a function or something like that.
class Coop():
objects = CoopManager()
name = models.CharField(max_length=250, null=False)
types = models.ManyToManyField(CoopType, blank=False)
...
proposed = models.JSONField("Proposed Changes", null=True)
def apply_proposed_changes(self):
proposed = self.proposed
self.name = proposed.get('name')
for type in proposed.get('types'):
self.types.add(CoopType.objects.get(name=type))
...
In any case if you're trying to inherit all the properties from Coop you need to understand how Django model inheritance work and all the caveats before you get bitten later down the track:
https://docs.djangoproject.com/en/4.0/topics/db/models/#model-inheritance

how to make a field unique based on another filed in django models?

I want to make a field unique based on another field in the same model, this is my model:
class Shop(models.Model):
name = models.CharField(max_length=50)
class Product(models.Model):
name = models.CharField(max_length=50, unique=True)
shop = models.ForignKey(Shop, on_delete=models.CASCADE)
I want the product's name to be unique only based on Shop, for example, if we have the product a from shop a, shop a can not make another product with the name a but shop b can make a product with name a.
for example we have name = models.CharField(unique_for_date=date_field) in models, which make the name unique for the date at date_field.
is there anything like unique_for_date?
can I handle this operation in models or I should try to handle it in view or form?
On your Product table:
class Product(...):
...
class Meta:
unique_together = ('shop', 'name')
This will ensure Products must have a unique name across the Shop they are related to.

Django dynamic form subclass list

I'm trying to understand how can I define model as a class containing 2 integers and 1 charfield and then make it a part of another model.
Example of data I need
I guess in object oriented programming I should define model class like this:
class Component(models.Model):
pipe_type = models.CharField(max_length=200)
length = models.IntegerField()
amount = models.IntegerField()
And then I don't know how can I use it with django models, it should be something like this:
class Item(models.Model):
name = models.CharField()
components_needed = ? LIST OF Component class ?
Also, since components needed size will wary for objects, it should be possible to extend it's size with button on a page, for example there could be 3 input fields and next to them would be "+" and "-" button to add/remove another set of 3 input fields
I spent entire day looking for solution, but at this point I'm not sure if django can handle this. I'm new to python and django, so there are many things I do not understand.
I will be grateful for any kind of help
the only way now( you canot put multi FK in one cell) is like django itself using with user/groups so you need 3 models.
in django there is group, user and user_group so i suggesting for you:
class Component(models.Model):
pipe_type = models.CharField(max_length=200)
length = models.IntegerField()
amount = models.IntegerField()
class Item(models.Model):
name = models.CharField()
class Item_Component(models.Model):
Component = models.ForeignKey(Component, on_delete=models.CASCADE)
Item = models.ForeignKey(Item, on_delete=models.CASCADE)
so now in third model you can have multiple rows with item and with diffrent component.
open yours db viewer app and see django user_group table.

join the results of two query on each others with Django

I have 2 models, i simplify them for the example:
class CustomerOrder(models.Model):
product = models.ForeignKey(Product, on_delete=models.PROTECT)
isPaid = models.BooleanField(default=False)
and
class EventParticipant(models.Model):
customerOrder = models.ForeignKey(CustomerOrder, on_delete=models.CASCADE)
event = models.ForeignKey(Product, on_delete=models.CASCADE)
What i need to do is to display in a table every participants for an event but link the order to the participant so i can display the isPaid status for each participant.
I think its similar to a join on SQL.
So i tried something like:
participants = EventParticipant.objects.filter(event=event_pk).select_related('customerOrder')
but when i try to access it like
participants.cusomerOrder
i get: 'QuerySet' object has no attribute 'customerOrder'
so i guess is missunderstand something.
Thanks
participants is an EventParticipant QuerySet, whcih is an iterable, So you need to iterate over it
for participant in participants:
print(participant.customerOrder.isPaid)

Resources