django-modeltranslate default language duplicate value - python-3.x

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?

Related

Wagatail Custom User models not displaying ModelChoiceField

Im using wagtail 4.1 & Django 4.1
I'm trying to create a custom User model which selects from a Snippet I have created.
class User(AbstractUser):
custiommodel= models.ForeignKey(CustomModel, on_delete=models.SET_NULL, null=True, blank=False)
user_type = models.CharField(blank=False, null=False, max_length=20, choices=USER_TYPE_CHOICES)
panels = [
FieldPanel('custommodel'),
FieldPanel('user_type'),
]
class CustomUserCreationForm(UserCreationForm):
user_type = forms.ChoiceField(required=True, choices=USER_TYPE_CHOICES, label=_("User Type"))
custommodel = forms.ModelChoiceField(queryset=CustomModel.objects, required=True,
label=_("Select Organisation"))
In my settings I have
WAGTAIL_USER_EDIT_FORM = 'users.forms.CustomUserEditForm'
This used to previously work on older versions of wagtail. Now the only custom filed i can see from above is 'user_type' which means it's finding the correct file but won't display custom models.
Is this related to this bug which won't allow me to directly register_snipets in the model file but instead in 'wagtail_hooks.py' through view sets?

Is it possible get two fields from parent model to one child model using foreign key?

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.

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.

how do I post a foreign key by some other field rather than primary key in django rest framework

I am developing a pet management api and this is what I post to the body when assigning a day of the week to a pet :
{
"day": "Sunday",
"pet_name": 2 <-- how to add pet name (rather than the primary key)(this is a foreign key)
}
How do I pass in the pet name which is the foreign key's field rather than the primary key field.
To avoid confusion I would rename the pet_name property of Day to just pet as it is referencing the Pet model.
class Day(models.Model):
pet = models.ForeignKey(Pet, on_delete=models.CASCADE, null=True)
In your DaySerializer you can then just use SlugRelatedField to be able to use the pet's name to reference the pet.
class DaySerializer(serializers.ModelSerializer):
pet_props = PropsSerializer(read_only=True, many=True)
pet = serializers.SlugRelatedField(slug_field='name')
class Meta:
model = models.Day
fields = ("id", "day", "pet", "pet_props")
The representation of this serializer will put the pet's name as value for the pet field. Also when writing, this allows you to use the pet's name to reference the pet instance which solves the actual issue in your question.
(You can technically also do pet_name = serializers.SlugRelatedField(slug_field='name'), but I would not do that to avoid confusion.)
I would recommend putting a unique constraint on your pet's name property though.
If you just want to display some readonly data, you can use SerializerMethodField:
from django.core.exceptions import ObjectDoesNotExist
class DaySerializer(serializers.ModelSerializer):
pet_name = serializers.SerializerMethodField()
def get_pet_name(self, obj):
try:
return obj.pet_name.name
except ObjectDoesNotExist:
# the day object doesn't have any
# pet associated, so return None
return None
Note: It would be better if you change the pet_name foreignkey to pet since it's holding a Pet instance, and not just its name.

Resources