I'm working on ModelSerializer I'm facing these below issues.
1) Unable to validate .validate(self, data) method as I want to return a custom validator message which is not working.
model.py
class BlogModel(models.Model):
BLOG_STATUS = (
('PUBLISH', 'Publish'),
('DRAFT', 'Draft'),
)
blog_id = models.AutoField(primary_key=True)
user = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='blogs')
title = models.CharField(max_length=255)
content = models.TextField(blank=True, null=True)
status = models.CharField(max_length=7, choices=BLOG_STATUS)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta():
db_table = 'blogs'
verbose_name = 'Blog'
verbose_name_plural = 'Blogs'
def __str__(self):
return self.title
serializers.py
import datetime
from django.contrib.auth.models import User
from django.utils.timezone import now
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer,Serializer
from blogs.models import BlogModel, BlogFilesModel
class UserSerializer(ModelSerializer):
class Meta:
model = User
fields = '__all__'
# exclude = ['password']
class BlogFilesSerializer(ModelSerializer):
count_files = serializers.IntegerField(required=False)
class Meta:
model = BlogFilesModel
fields = ('blog_files_id', 'blog', 'path',
'created_at', 'updated_at', 'count_files')
def get_path(self, obj):
formatted_date = obj.created_at.strftime("%d-%m-%Y")
return formatted_date
class BlogSerializer(ModelSerializer):
blog_files = serializers.SerializerMethodField()
def get_blog_files(self, obj):
info = BlogFilesSerializer(BlogFilesModel.objects.filter(
blog=obj).order_by('-pk'), many=True)
if info.data:
for i in info.data:
user_detail = User.objects.get(pk=obj.user.id)
i.__setitem__('user_detail', UserSerializer(user_detail).data)
if i.get('user_detail'):
try:
del i['user_detail']['password']
except expression as identifier:
pass
return info.data
blog_created_at=serializers.SerializerMethodField()
def get_blog_created_at(self, obj):
formatted_date=obj.created_at.strftime("%d-%m-%Y")
return formatted_date
def validate(self, data):
if data.get('title') == "":
#this below error message not showing
raise serializers.ValidationError("Title field must not be left blank.")
return data
def validate_title(self, value):
if value != "Hello":
raise serializers.ValidationError("Title field must be 'Hello' ")
return value
def validate_content(self, value):
if len(value) < 2:
raise serializers.ValidationError("Content must have at least 2 letters")
return value
class Meta:
model=BlogModel
fields=('blog_id', 'user', 'title', 'content',
'status', 'blog_files', 'blog_created_at')
views.py
class BlogViewSet(viewsets.ModelViewSet):
queryset = BlogModel.objects.all()
lookup_field = 'blog_id'
serializer_class = BlogSerializer
below is the screen shot of my output
Hope is have explained my problem well.
Thank you.
You can define extra_kwargs in the class Meta of your serializer to customize error messages.
https://www.django-rest-framework.org/api-guide/serializers/#additional-keyword-arguments
In your case, you would add this to BlogSerializer:
extra_kwargs = {
'title': {
'error_messages': {
'blank': 'my custom error message for title'
}
}
}
The tricky part might be figuring out the key you need to override. Getting the errors raised by the validators in the serializer can be done in the django shell. For example.
serializer = BlogSerializer(data={'title':''})
serializer.is_valid()
serializer._errors
{'status': [ErrorDetail(string=u'This field is required.', code=u'required')]
'title': [ErrorDetail(string=u'This field may not be blank.', code=u'blank')
'user': [ErrorDetail(string=u'This field is required.', code=u'required')]}
ErrorDetail.code is the key for the error_messages dictionary. In this case, it is 'blank'.
Related
I'm trying to make my nested serializer to be able to process updating when I'm only updating for the parent model. The default action in drf is that the serializer cant tell if ur child model is trying to updating or create, there's a solution where you just turn off the validation, which I don't think is ideal for the database and iots implication.
I've scour about this topic for like 2 days and I think the ideal approach to this is to override the is_valid method to be able to just return the object.
Idea from :
Django REST Framework ModelSerializer get_or_create functionality
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
class MyModelSerializer(serializers.ModelSerializer):
def is_valid(self, raise_exception=False):
if hasattr(self, 'initial_data'):
# If we are instantiating with data={something}
try:
# Try to get the object in question
obj = Security.objects.get(**self.initial_data)
except (ObjectDoesNotExist, MultipleObjectsReturned):
# Except not finding the object or the data being ambiguous
# for defining it. Then validate the data as usual
return super().is_valid(raise_exception)
else:
# If the object is found add it to the serializer. Then
# validate the data as usual
self.instance = obj
return super().is_valid(raise_exception)
else:
# If the Serializer was instantiated with just an object, and no
# data={something} proceed as usual
return super().is_valid(raise_exception)
class Meta:
model = models.MyModel
The problem is whenever I try to implment I get the error:
Field 'id' expected a number but got [{'id': 18, 'title': 'aDDD', 'body': 'aDDD', 'slug': 'aDDDbabe', 'author': 1, 'question': 25}].
obj = Question.objects.get(**self.initial_data)
This code triggers it, however When I
obj = Question.answers.get(**self.initial_data)
I get 'ReverseManyToOneDescriptor' object has no attribute 'get' .
Since mine is a nested serializer I would have to find another way to make this work. Any advice where I can fix it? :(
serializers.py
from rest_framework import serializers
# https://github.com/encode/django-rest-framework/blob/3.12.4/rest_framework/serializers.py#L839
from rest_framework.fields import ( # NOQA # isort:skip
CreateOnlyDefault, CurrentUserDefault, SkipField, empty
)
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from .models import Question, Answer
class AnswerSerializer(serializers.ModelSerializer):
"""Serialize Answer model"""
class Meta:
model = Answer
fields = ('id','title', 'body', 'slug', 'author', 'question')
# https://stackoverflow.com/questions/57249850/overwriting-nested-serializers-create-method-throws-typeerror-create-got-mul
read_only_fields = ('question',)
lookup_field = 'slug'
# https://stackoverflow.com/questions/55031552/how-to-access-child-entire-record-in-parent-model-in-django-rest-framework
class QuestionSerializer(serializers.ModelSerializer):
"""Serialize Question model"""
#This answer variable and the fields 'answer' you refer to has to be the SAME but
#These can change exp: 'aaa'
answers = AnswerSerializer(read_only=False, many=True,)
class Meta:
model = Question
fields = ('id','title', 'body', 'slug', 'author', 'category', 'answers',)
lookup_field = 'slug'
def is_valid(self, raise_exception=False):
if hasattr(self, 'initial_data'):
# If we are instantiating with data={something}
try:
# Try to get the object in question
obj = Question.objects.get(**self.initial_data)
except (ObjectDoesNotExist, MultipleObjectsReturned):
print("LOLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL")
return print(obj)
else:
print("LOLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL")
print(obj)
else:
return super().is_valid(raise_exception)
def create(self, validated_data):
answers_data = validated_data.pop('answers')
question = Question.objects.create(**validated_data)
for answer_data in answers_data:
#The above stackoverflow link at the answer serializers is realted to this
Answer.objects.create(question=question, **answer_data)
return question
def update(self, instance, validated_data):
instance.title = validated_data.get('title', instance.title)
instance.body = validated_data.get('body', instance.body)
instance.slug = validated_data.get('slug', instance.slug)
instance.author = validated_data.get('author', instance.author)
instance.category = validated_data.get('category', instance.category)
instance.save()
# https://django.cowhite.com/blog/create-and-update-django-rest-framework-nested-serializers/
answers_data = validated_data.pop('answers')
aas = (instance.answers).all()
print("######")
print(aas)
print("######")
print(instance.answers.get().slug)
print("#########################################")
aas2 = list(aas)
print("######")
for f in validated_data:
print(f)
print(validated_data.items())
print(dir(validated_data))
print("######")
for answer_data in answers_data:
aas3 = aas2.pop(0)
aas3.title= answer_data.get('title', aas3.title)
aas3.body= answer_data.get('body', aas3.body)
aas3.slug= answer_data.get('slug', aas3.slug)
aas3.author= answer_data.get('author', aas3.author)
aas3.question= answer_data.get('question', aas3.question)
aas3.save()
return instance
views.py
from django.shortcuts import render
from .models import Question, Answer
from django.conf import settings
from rest_framework import viewsets
from rest_framework.authentication import TokenAuthentication
from .serializers import QuestionSerializer
#from .permissions import UpdateOwnPrice
from rest_framework.permissions import IsAdminUser
class QuestionViewSet(viewsets.ModelViewSet):
"""CRUD """
serializer_class = QuestionSerializer
queryset = Question.objects.all()
authentication_classes = (TokenAuthentication,)
#permission_classes = (UpdateOwnPrice,)
lookup_field = 'slug'
extra_kwargs = {'slug': {'validators': []},}
models.py
from django.db import models
from django.conf import settings
from django.db.models import Q
from django.utils import timezone
from django.urls import reverse
class Category(models.Model):
name= models.CharField(max_length=100)
def __str__(self):
return self.name
class Question(models.Model):
title= models.CharField(max_length= 100)
body= models.TextField()
slug= models.SlugField(unique= True)
date_posted= models.DateTimeField(default=timezone.now)
author= models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.CASCADE, related_name = 'questions')
category= models.ForeignKey(Category, on_delete= models.CASCADE, related_name = 'questions')
#objects= QnAManager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('home')
class Answer(models.Model):
title= models.CharField(max_length= 100)
body= models.TextField()
slug= models.SlugField(unique= True)
date_posted= models.DateTimeField(default=timezone.now)
author= models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.CASCADE, related_name = 'answers')
question= models.ForeignKey(Question, on_delete= models.CASCADE, related_name = 'answers')
#objects= QnAManager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('home')
I would like to know how can I add a new value to my request.data
this is my request.data, structure:
[{'fname': 'john', 'lname': 'Doe'}]
how can I add the age key for example
This is my whole code :
def create(self, request):
formSerializer = self.serializer_class(data = request.data)
#### look Down
request.data['master'] = self.request.user.id
#######
if formSerializer.is_valid():
formSerializer.save()
objectSerializer = TeamSerializer(Team.objects.all(), many=True)
return Response(objectSerializer.data, status =
status.HTTP_201_CREATED)
return Response(formSerializer.errors, status.HTTP_400_BAD_REQUEST)
this is my model
from django.db import models
from users.models import CustomUser
# Create your models here.
class Team(models.Model):
master = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
name = models.CharField(null=False, blank=False, max_length=255)
comment = models.CharField(null=True, blank=True, max_length=255)
i have two input fields ( name + comment ) so i need master field that's why
Here you have to not need to add mater in request.data.
Try this:
def create(self, request):
formSerializer = self.serializer_class(data = request.data)
# request.data['master'] = self.request.user.id
if formSerializer.is_valid():
formSerializer.save(master = self.request.user)
objectSerializer = TeamSerializer(Team.objects.all(), many=True)
return Response(objectSerializer.data, status =
status.HTTP_201_CREATED)
return Response(formSerializer.errors, status.HTTP_400_BAD_REQUEST)
Remove master from serializer's fields
and add this in serializer:
class MYSerializer(serializers.ModelSerializer):
username = serializers.CharField(source='master.username',read_only=True)
class Meta:
model = MY_MODEL
fields = (OTHER_FIELDs,'username')
Source Mean??
serializer.py
from rest_framework import serializers
from status.models import Status
class StatusSerializer(serializers.ModelSerializer):
class Meta:
model = Status
fields = [
'user',
'content',
'image'
]
def validate(self, data):
content = data.get('content', None)
if content == '':
content = None
image = data.get('image', None)
if content is None and image is None:
raise serializers.ValidationError('Content or image is required.')
return data
views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from status.models import Status
from .serializers import StatusSerializer
class StatusListSearchAPIView(APIView):
permission_classes = []
authentication_classes = []
def get(self, request):
qs = Status.objects.all()
serializer = StatusSerializer(qs)
print(serializer)
return Response(serializer.data)
models.py
from django.db import models
from django.conf import settings
def upload_status_image(instance, filename):
return "updates/{user}/{filename}".format(user=instance.user, filename=filename)
class StatusQuerySet(models.QuerySet):
pass
class StatusManager(models.Manager):
def get_queryset(self):
return StatusQuerySet(self.model, using=self._db)
class Status(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, )
content = models.TextField(null=True, blank=True)
image = models.ImageField(upload_to=upload_status_image, null=True, blank=True)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
objects = StatusManager()
def __str__(self):
return str(self.content)[:50]
class Meta:
verbose_name = 'Status post'
verbose_name_plural = 'Status posts'
error:
AttributeError: Got AttributeError when attempting to get a value for field user on serializer StatusSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the StatusQuerySet instance.
Original exception text was: 'StatusQuerySet' object has no attribute 'user'.
In views.py
Change this line :
serializer = StatusSerializer(qs)
to this line:
serializer = StatusSerializer(qs, many=True)
I am a beginner in Django. Right now, I am working with the APIs. I am facing a problem. I can't view the string value one of the fields, called label, at http://127.0.0.1:8000/gameapi/. Instead of seeing "label_tag": "racing", I am seeing "label_tag": [2]. Here is the screenshot:
Here are my codes of serializers.py located inside gamreview folder.
from rest_framework import serializers
from .models import Game, Tags
# class TagSerializer(serializers.ModelSerializer):
# class Meta:
# model = Tags
# fields = ['label']
class GameSerializer(serializers.ModelSerializer):
# label_tag = TagSerializer(many=True)
class Meta:
model = Game
# fields = ['id', 'title', 'developer', 'platform']
fields = ['id', 'title', 'developer', 'platform','label_tag']
def create(self, validated_data):
label_tag_data = validated_data.pop('label_tag')
game = Game.objects.create(**validated_data)
for tags_data in label_tag_data:
Tags.objects.create(game=game, **tags_data)
return Game.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.title = validated_data.get('title', instance.title)
instance.developer = validated_data.get('developer', instance.developer)
instance.platform = validated_data.get('platform', instance.platform)
# instance.tag = TagSerializer(read_only=True, many=True)
instance.save()
return instance
Here are my codes of models.py under gamreview folder:
from django.db import models
from django.template.defaultfilters import slugify
# Create your models here.
class Tags(models.Model):
label = models.CharField(max_length=20)
def __str__(self):
return self.label
class Game(models.Model):
title = models.CharField(max_length=100)
developer = models.CharField(max_length=100)
platform = models.CharField(max_length=50, default='null')
label_tag = models.ManyToManyField(Tags)
slug = models.SlugField(max_length=150, default='null')
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super().save(*args, **kwargs)
class Review(models.Model):
game = models.ForeignKey(Game, on_delete=models.CASCADE)
review = models.CharField(max_length=1000)
date = models.DateField(auto_now=True)
slug = models.SlugField(max_length=150, default='null')
def __str__(self):
return self.game
Here are my codes of views.py under gamreview folder:
from django.views import generic
from .models import Game
from rest_framework import generics
from .serializers import GameSerializer
# Create your views here.
class GameListView(generic.ListView):
template_name = 'gamereview/gamelist.html'
context_object_name = 'all_games'
def get_queryset(self):
return Game.objects.all()
class ReviewView(generic.DetailView):
model = Game
template_name = 'gamereview/review.html'
# class GameApiView(generics.ListAPIView):
class GameApiView(generics.ListCreateAPIView):
queryset = Game.objects.all()
serializer_class = GameSerializer
class GameDetailApiView(generics.RetrieveUpdateDestroyAPIView):
queryset = Game.objects.all()
serializer_class = GameSerializer
Here are my codes of urls.py under gamreview folder:
from . import views
from django.urls import path
app_name = 'gamereview'
urlpatterns = [
path('gamereview/', views.GameListView.as_view(), name='gamelist'),
path('gamereview/<slug:slug>/', views.ReviewView.as_view(), name='review'),
path('gameapi/', views.GameApiView.as_view(), name='gamelistapi'),
path('gameapi/<int:pk>/', views.GameDetailApiView.as_view()),
]
I don't get any error while running the server. However, "label_tag": "racing"is not showing up.
How can I fix the issue?
in Game model change label_tag to
label_tag = models.ManyToManyField(Tags, related_name='tags')
this can be considered as tags is a field for a Game model
your serializer classes should be
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tags
fields = ['label']
class GameSerializer(serializers.ModelSerializer):
tags= TagSerializer(many=True)
class Meta:
model = Game
# fields = ['id', 'title', 'developer', 'platform']
fields = ['id', 'title', 'developer', 'platform','tags']
you will get tags as a list of tags objects every tag have a label field with string value
'tags': [
{
'label': 'etc'
},
{
'label': 'etc2'
}
]
if you want tags like
'tags': [
'etc',
'etc'
]
this code will help you
```python
class GameSerializer(serializers.ModelSerializer):
label_tags = serializers.SerializerMethodField()
class Meta:
model = Game
# fields = ['id', 'title', 'developer', 'platform']
fields = ['id', 'title', 'developer', 'platform','label_tags']
def get_label_tags(self, game):
new_tags = []
tags = game.label_tag.all()
for tag in tags:
new_tags.append(tag.label)
return new_tags
You can use the source argument
class GameSerializer(serializers.ModelSerializer):
label_tag = serializers.ReadOnlyField(source='label.label')
class Meta:
model = Game
fields = ['id', 'title', 'developer', 'platform','label_tag']
another way is to use a SerializerMethodField like this(it's an overkill in this case I believe)
class GameSerializer(serializers.ModelSerializer):
label_tag = serializers.SerializerMethodField()
class Meta:
model = Game
fields = ['id', 'title', 'developer', 'platform','label_tag']
def get_label_tag(self, obj):
return obj.label.label
check similar answers here DRF source argument
I'm a little new to Django and Django-REST so please bear with me. Perhaps the answer is in the documentation, so if I missed it, apologies in advance.
Goal: I would like to create an EquipmentInfo object whose attributes include pre-existing foreign keys (EquipmentType and EquipmentManufacturer).
models.py
class EquipmentType(models.Model):
equipment_type = models.CharField(verbose_name="Equipment Type", max_length=50, unique=True)
def __unicode__(self):
return self.equipment_type
class EquipmentManufacturer(models.Model):
manufacturer_name = models.CharField(verbose_name="Manufacturer Name", max_length=50, unique=True)
def __unicode__(self):
return self.manufacturer_name
class EquipmentInfo(models.Model):
equipment_type = models.ForeignKey(EquipmentType, verbose_name="Equipment Type")
part_identifier = models.CharField(verbose_name="Machine ID (alias)", max_length=25)
manufacturer_name = models.ForeignKey(EquipmentManufacturer, verbose_name="Manufacturer Name")
serial_number = models.CharField(verbose_name="Serial Number", max_length=25)
date_of_manufacture = models.DateField(verbose_name="Date of Manufacture", default=date.today)
is_active = models.BooleanField(verbose_name="Is Active", default=True)
def __unicode__(self):
return self.part_identifier
serializers.py
class EquipmentTypeSerializer(serializers.ModelSerializer):
class Meta:
model = EquipmentType
fields = ('id', 'equipment_type',)
class EquipmentManufacturerSerializer(serializers.ModelSerializer):
class Meta:
model = EquipmentManufacturer
fields = ('id', 'manufacturer_name',)
class EquipmentInfoSerializer(serializers.ModelSerializer):
class Meta:
model = EquipmentInfo
fields = ('id', 'equipment_type', 'part_identifier', 'manufacturer_name','serial_number', 'date_of_manufacture', 'is_active')
equipment_type = EquipmentTypeSerializer(many=False)
manufacturer_name = EquipmentManufacturerSerializer(many=False)
def create(self, validated_data):
equipment_type = validated_data.pop('equipment_type')
manufacturer_name = validated_data.pop('manufacturer_name')
equipment_info = EquipmentInfo.objects.create(**validated_data)
return equipment_info
Assuming I already have relevant EquipmentType and EquipmentManufacturer objects created, I would like to add another EquipmentInfo object. What is the appropriate way to set up my EquipmentInfo serializer so that I can pass in information such as
{
"equipment_type":{
"equipment_type":"already_created",
},
"part_identifier":"something_new",
"manufacturer_name":{
"manufacturer_name":"already_created"
},
"serial_number":"WBA1",
"date_of_manufacture": "1900-01-01",
"is_active":true
}
or even better:
{
"equipment_type":"already_created",
"part_identifier":"something_new",
"manufacturer_name":"already_created",
"serial_number":"WBA1",
"date_of_manufacture": "1900-01-01",
"is_active":true
}
Any help is appreciated.
I have also faced the problem ,and have solved it ,the following is my step ,hope it will be helpful
1.company Model and contact model as follows:
class Company(models.Model):
Company_Name = models.CharField(u'Company Name',max_length=255, default="")
Modified_By = models.CharField(u'Modified By',max_length=255, default="")
class Company_Contact(models.Model):
Company = models.ForeignKey(Company)
Last_Name = models.CharField(u'Last Name',max_length=255, default="")
First_Name = models.CharField(u'First Name',max_length=255, default="")
2.I create A New Serializer Named CompanyReferenceSerializer,and company_contact
class CompanyReferenceSerializer(serializers.ModelSerializer):
class Meta:
model = Company
fields = ['id', 'Company_Name', 'Company_Name_SC']
class CompanyContactSerializer(serializers.ModelSerializer):
Company = CompanyReferenceSerializer()
class Meta:
model = Company_Contact
fields = ['Company', 'Last_Name','First_Name']
extra_kwargs = {
'Company': {'allow_null': True, 'required': False},
'Last_Name': {'allow_null': True, 'allow_blank': True, 'required': False},
'First_Name': {'allow_null': True, 'required': False, 'allow_blank': True},
}
3.Viewset as follows,in the backend,I get the object Namedcompany_instanceaccording to the 'company_id'
class CompanyContactViewSet(viewsets.ModelViewSet):
serializer_class = CompanyContactSerializer
def create(self, validated_data):
serializer = self.get_serializer(data=self.request.data)
company_id_for_contact = self.request.data.pop('Company_id')
company_instance = Company.objects.filter(id=company_id_for_contact).first()
if not serializer.is_valid():
print serializer.errors
data = serializer.validated_data
serializer.save(Company=company_instance)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
and I success insert one record in the company_contact ,Hope it can help you !
Using nested serializers makes it really hard for posts (if it even works, as it didn't used to work), and given your simple models, I would recommend just removing them.
I will recommend you add APIs for
/api/v1/type
/api/v1/manufacturer
/api/v1/info
(or whatever names you want to use). The type and manufacturer ones should be vanilla views and using your existing serializers.
For info, remove the two nested serializers:
class EquipmentInfoSerializer(serializers.ModelSerializer):
class Meta:
model = EquipmentInfo
fields = ('id', 'equipment_type', 'part_identifier', 'manufacturer_name','serial_number', 'date_of_manufacture', 'is_active')
After that, you should be able to do post using:
data = {
"equipment_type": 5, # The ID of the equipment type record
"part_identifier":"something_new",
"manufacturer_name": 10 # The ID of the manufacturer record
"serial_number":"WBA1",
"date_of_manufacture": "1900-01-01",
"is_active":true
}
In my case, I do like making it the GETs more convenient so I add read-only fields to return a name (or even the whole serialized record):
class EquipmentInfoSerializer(serializers.ModelSerializer):
type_name = serializers.SerializerMethodField(read_only=True)
class Meta:
model = EquipmentInfo
fields = ('id', 'equipment_type', 'part_identifier', 'manufacturer_name','serial_number', 'date_of_manufacture', 'is_active')
def get_type_name(self, obj):
return obj.equipment_type.equipment_type
Hope this helps.