My main model class looks like this:
class Article(models.Model): title = models.CharField(max_length=120) content = models.TextField() authors = models.TextField(max_length=200) year = models.IntegerField() form = models.TextField(choices=FORMS) language = models.TextField(choices=LANGUAGES) region = models.TextField(choices=REGIONS) tags = models.TextField() def __str__(self): return self.title
And, for my api to send backend data to front end, I have a serializers
class that looks like this:
class ArticleSerializers(serializers.ModelSerializer): class Meta: model = Article fields = ('id', 'title', 'content', 'authors', 'year'...)
Clearly, the current way of writing fields
as a bunch of hard-coded strings is very clumsy and prone to mistake (since I might change the fields in Article
class but forget to update the fields
in the serializer).
So my question is, how can I improve the style of fields
?
Also, another side question, what is this type of coding rule / principle called, when you try to make one part of the code to be dependent on the other, so you need to change one part, instead of always having to remember changing both parts?
Thanks!
Advertisement
Answer
The documentation on specifying which fields to include [drf-doc] says:
You can also set the fields attribute to the special value
'__all__'
to indicate that all fields in the model should be used.
We thus can include all fields with:
class ArticleSerializers(serializers.ModelSerializer): class Meta: model = Article fields = '__all__'
If you want to exclude certain fields, you can work with an exclude
option:
You can set the
exclude
attribute to a list of fields to be excluded from the serializer.
So if you want to exclude the tags
for example, you can work with:
class ArticleSerializers(serializers.ModelSerializer): class Meta: model = Article exclude = ['tags']
Clearly, the current way of writing fields as a bunch of hard-coded strings is very clumsy and prone to mistake
Normally the metaclass logic will raise an exception if it can not find that field when it constructs the class, so when you start the application. This thus means that typos will not result in any problems. The only thing that could go wrong is specifying another field that exists for the given model.