I use rest framework, I have field in user emloyee.company which is has field name. I need display only name string, but I have dict.
class CompanySerializer(serializers.ModelSerializer):
class Meta:
model = Company
fields = ('name',)
class UserSerializer(MySerializer):
company = CompanySerializer(source='employee.company')
class Meta:
fields = (..., 'company')
I've got:
{...,"company":{"name":"My company"}}
I need:
{...,"company":"My company"}
Thanks for any help.
Change:
company = CompanySerializer(source='employee.company')
to:
company = serializers.ReadOnlyField(source='employee.company.name')
Related
My model looks like this.
class Student(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
roll_no = models.CharField(max_length=32)
course = models.CharField(max_length=120)
Now I want to make a filter form using django_filters and want to use distinct values of course field as choices of select input but it requires each value to be associated with unique id and this field doesn't have any unique id.
I tried this:
class StudentFilter(django_filters.FilterSet):
course = django_filters.ModelChoiceFilter(queryset=Student.objects.values("course",flat = True).distinct(),empty_label=('Course'))
class Meta:
model = Student
fields = []
but it didn't work.
Note I do not want to make separate model for course.
The AllValuesFilter does exactly what you are asking for I believe
class StudentFilter(django_filters.FilterSet):
course = django_filters.AllValuesFilter(field_name="course")
class Meta:
model = Student
fields = []
I have two models where employee have relation with person model but person have no relation with employee model.
Like:
class Person(models.Model):
name = models.CharField(max_length=100)
address = models.CharField(max_length=100)
class Employee(models.Model):
person = models.ForeignKey(Person, related_name='person_info')
code = models.CharField()
In such cases I want code field data in person serializer.
I can solved this with writing method in person model or using SerializerMethodField in person serializer
like this:
def get_employee_code(self):
return Employee.objects.get(person=self).id
and add this as source in person serializer
employee_code = serializers.CharField(source='get_employee_code')
Or adding employee serializer into person serialiszer
class PersonSerializer(serializers.ModelSerializer):
employee = EmployeeSerializer()
class Meta:
model = Person
fields = ('name', 'address', 'employee')
But i was trying to do this with reverse relation but i can't. I have tried like this, it gives an error
Serializer:
class PersonSerializer(serializers.ModelSerializer):
employee_code = serializers.CharField(source='person_info.code')
class Meta:
model = Person
fields = ('name', 'address', 'employee_code')
How can i solve this with reverse relation?
At the moment because you are using a ForeignKey field on the person attribute, it means that its returning a list when you access the reverse relation.
One solution would be to use a slug related field, though this must have many and read_only set to True, and will return a list because of the ForeignKey field.
class PersonSerializer(serializers.ModelSerializer):
employee_code = serializers.SlugRelatedField(
source='person_info',
slug_field='code',
many=True,
read_only=True,
)
class Meta:
model = Person
fields = ('name', 'address', 'employee_code')
The other option is to change your ForeignKey into a OneToOneField, which would still need read_only set to True but it will not return a list.
class Person(models.Model):
name = models.CharField(max_length=100)
address = models.CharField(max_length=100)
class Employee(models.Model):
person = models.OneToOneField(Person, related_name='person_info')
code = models.CharField()
class PersonSerializer(serializers.ModelSerializer):
employee_code = serializers.SlugRelatedField(
source='person_info',
slug_field='code',
read_only=True,
)
class Meta:
model = Person
fields = ('name', 'address', 'employee_code')
Or, if you don't want to change the ForeignKey, you could add a employee_code property method to the model instead to return the first employee code in the person_info relation.
class Person(models.Model):
name = models.CharField(max_length=100)
address = models.CharField(max_length=100)
#property
def employee_code(self):
employees = self.person_info.filter()
if employees.exists():
return employees.first().code
return ''
class Employee(models.Model):
person = models.OneToOneField(Person, related_name='person_info')
code = models.CharField()
class PersonSerializer(serializers.ModelSerializer):
employee_code = serializers.CharField(
read_only=True,
)
class Meta:
model = Person
fields = ('name', 'address', 'employee_code')
you can access the reverse relation with custom SerializerMethodField()
class PersonSerializer(serializers.ModelSerializer):
employee_code = serializers.SerializerMethodField()
def get_employee_code(self, obj):
return obj.person_info.code
class Meta:
model = Person
fields = ('name', 'address', 'employee_code')
I have two models:
class Vehicle(Model):
name = models.CharField(max_length=50)
class Driver(Model):
vehicle = models.ForeignKey(Vehicle, related_name='owned_vehicle')
name = models.CharField(max_length=100)
now on my forms.py:
class MyForm(forms.Form):
drivers = Driver.objects.order_by('name')
drivers_list = forms.ModelChoiceField(drivers, empty_label='* Driver *', label='Driver')
The problem is drivers_list also includes the vehicles in the list.
How can I prevent this form from including the ForeignKey field into the ModelChoiceField?
Why are you not using model form for drivers,
class DriverForm(forms.ModelForm):
class Meta:
model = Article
fields = ['name', 'vehicle']
For your own forms,
class MyForm(forms.Form):
driver_list = forms.ModelChoiceField(queryset=Driver.objects.order_by('name'))
# then other attributes which you want to map with driver
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.