I have a use case where in UserProfile model, user details are stored. One of the field is user_company_name.
class UserProfile(BaseModel):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
user_company_name = models.CharField(max_length=254)
Instead of a CharField I want the field to be a ChoiceField, having drop down of the Company (names) currently present in the database. If the current company of the user is not present in the dropdown I plan to give the user an option to add his or her company to the DB.
Suppose I have a Company model as such:
class Company(BaseModel):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
What should be my Field Choice in the UserProfile model for user_company_name field.
Why don't just add ForeignKey to UserProfile model? Example below.
class UserProfile(BaseModel):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
user_company = models.ForeignKey(Company)
You need ForeignKey for this field
user_company_name
https://docs.djangoproject.com/en/1.10/ref/models/fields/#foreignkey
read this doc
You can use foreign key in the models for user_company and in forms use ChoiceField to get a drop down.
Check the code below:-
In models:-
class UserProfile(BaseModel):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
user_company = models.ForeignKey(Company)
In Forms:-
user_company = forms.ModelChoiceField(queryset=Company.objects.all())
Related
class Patient(models.Model):
user = models.OneToOneField(User, related_name='patient', on_delete=models.CASCADE)
id_type = models.CharField(max_length=300)
id_number = models.CharField(max_length=300)
creation_date = models.DateField(default=datetime.date.today)
class Allergie(models.Model):
name = models.CharField(max_length=300, default="X")
class PatientAllergies(models.Model):
patient = models.ForeignKey(Patient, related_name="patient_allergies", on_delete=models.CASCADE)
allergie = models.ForeignKey(Allergie, on_delete=models.CASCADE, null=True)
professional_contract = models.ForeignKey(ProfessionalContract, null=True ,on_delete=models.CASCADE)
Is it possible to retrieve a patient objecto with a property that is a list of all his allergies, including name and id with these models?
you have the PatientAllergies as a chain,
so
patientAllergies = PatientAllergies.objects.get(patient.id_number='0000')
patientAllergies.allergie #you get the single allergie model connect with it, take care it is a foreignKey so it is singolar and not many
patientAlleriges.patient.user #will give you access to all the data of the user
You can achieve this with prefetch_related and Prefetch like so:
Patient.objects.prefetch_related(
Prefetch('patient_allergies__allergie', to_attr='allergies')
)
EDIT: Just learned that to_attr will not work on multiple levels of prefetch. Another approach I can think of is use a model property for Patient that returns its related allergies like this:
class Patient(models.Model):
#property
def allergies(self):
return Allergie.objects.filter(patientallergies_set__patient=self)
Then in your serializer, the allergies field can use the Allergies serializer
I am creating a project in django in which I have two diff users i.e. Customers and restaurants.
I am creating a model for Menu in which I want add to add restaurant name in models directly(user name in this case) instead of taking input thorough forms every time.Also if possible if can take name from another field like this which is part of login system?
Models.py
class menu_details(models.Model):
restaurant_name = models.CharField(blank=True, max_length=20)
dish_name = models.CharField(blank=True, max_length=20)
dish_type = models.CharField(max_length=10, choices=food_type, default='veg')
price = models.CharField(blank=True, max_length=20)
description = models.TextField(blank=True, max_length=5000)
image = models.ImageField0(blank=True)
class Meta:
db_table = "menu_details"
If I understand well what you want, I think you need a Foreign Key Field pointing to the User infromation.
field_name= models.ForeignKey(User, help_text="", blank=True, null=True, on_delete=models.CASCADE)
Then you can access all the data from a user instance in views, for example:
this_menu = menu_details.objects.get(pk=1)
restaurant_name = this_menu.field_name.first_name
restaurant_email = this_menu.field_name.email
Or in templates:
{{ this_menu.field_name.first_name }}
{{ this_menu.field_name.email}}
The requirement is "I want to insert person with the person groups selection and also at the time of Creating person group I can choose persons for that particular group".
I've added two models in my models.py and manage many to many relationship between.
models.py
from django.db import models
class PersonGroup(models.Model):
id = models.AutoField(primary_key=True)
groupName = models.CharField(max_length=30)
detail = models.CharField(max_length=200)
class Person(models.Model):
id = models.AutoField(primary_key=True)
personId = models.CharField(max_length=20)
personName = models.CharField(max_length=20)
state = models.IntegerField()
personGroup = models.ManyToManyField(PersonGroup, related_name="person_list", blank=True)
serializers.py
class PersonSerializer(serializers.ModelSerializer):
personGroup = serializers.PrimaryKeyRelatedField(queryset=PersonGroup.objects.all(), many=True)
class Meta:
model = Person
fields = '__all__'
class PersonGroupSerializer(serializers.ModelSerializer):
person_list = PersonSerializer(many=True, read_only=True)
class Meta:
model = PersonGroup
fields = '__all__'
The above code help me to create person with personGroup selection
But, I also want to add persons selection at the time of create personGroup. Currently at the time of creating personGroup I'm not allowed to enter persons.
Please let me know if there any solution by which I can also select available persons at the time of person group creation.
Your person_list field in the PersonGroupSerializer is on read only, so you can't modify it using the API.
person_list = serializers.PrimaryKeyRelatedField(queryset=Person.objects.all(), many=True)
Try removing this arg.
You might also want to switch to a ForeignKey field instead of slugged.
I'm using django-tables-2 for a project. I have a table that uses a model for displaying data but I need to add one more column to display some informations from another table. Can I do that?
Have you tried the following?
# models.py
class Person(models.Model):
" This is your regular model "
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
user = models.ForeignKey("auth.User")
dob = models.DateField()
class PersonTable(tables.Table):
id = tables.Column(name="id") # just add a field here
class Meta:
model = Person
You map the column either by having the same name of the model's attribute, either using the accessor property.
I guess in your case it would be:
class UsersTable(tables.Table):
custom = Column(_("Custom"), accessor='id', orderable=False) # Any attr will do, dont mind it
def render_custom(self, record):
return services.get_some_info(record)
class Meta:
model = User
fields = (b'username', )
I have form which generates from model
class UserProfile(models.Model):
company = models.ForeignKey(Company)
user = models.OneToOneField(User)
department = models.CharField(max_length=100)
position = models.CharField(max_length=100)
class UserProfileForm(ModelForm):
company_id = ModelChoiceField(queryset=Company.objects.all(),
widget=HiddenInput())
class Meta:
model = UserProfile
exclude = ('user')
But it's doesn't work, and company_id is stay visible select field.
How I can create hidden field with company id ?
fieldnames between model and form should match. Use company in stead of company_id and it'll work.