I'm new to django rest and today encounted a little trouble: Let's say we have two models:
class Tags(models.Model):
tag_text = models.CharField(name='tag', max_length=30)
and
class Entries(models.Model):
entry_header = models.CharField(name='header', max_length=30)
pub_date = models.DateTimeField(auto_now_add=True)
entry_text = models.TextField(blank=True, null=True)
entry_tags = models.ManyToManyField(Tags, related_name='entries', blank=True)
I can set blank property for Entries model, but have difficulty with doing the same to Tags. This way when I'm trying something like
http --json POST http://127.0.0.1:8000/tags/ tag_text="tag with no entry"
it returns me
"entries": [ This field is required ]
Is there any way I can creatre Tags object with blank "entries" field in this case?
Thank you in advance!
...and please note that
http --json POST http://127.0.0.1:8000/entries/ header="entry with no tags"
gives desired response
serializers from rest_framework would be quite simple in this case as well:
class EntriesSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Entries
fields = ('url', 'header', 'entry_text', 'pub_date', 'entry_tags')
class TagsSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Tags
fields = ('url', 'tag', 'entries')
and here are our views (viewsets from rest_framework to make it quick):
class EntriesView(viewsets.ModelViewSet):
queryset = Entries.objects.all()
serializer_class = EntriesSerializer
class TagsView(viewsets.ModelViewSet):
queryset = Tags.objects.all()
serializer_class = TagsSerializer
All go throught default router (from rest_framework.routers import DefaultRouter):
router = DefaultRouter()
router.register(r'entries', views.EntriesView)
router.register(r'tags', views.TagsView)
urlpatterns = [
url(r'^', include(router.urls)),
]
Eventually problem appeared to be in Serializer, not in Model itself. field property required=False should be used to emphasize that field is not mandatory during object creation if it wasn't specified during model description (and this way cannot be properly serialized).
class TagsSerializer(serializers.HyperlinkedModelSerializer):
entries = EntriesSerializer(many=True, required=False)
class Meta:
model = Tags
fields = ('url', 'tag', 'entries')
Thanks to everyone responded to guide me in a right direction!
>>> from testapp.models import Tags, Entries
>>> t = Tags.objects.create(tag = 'TAG')
>>> t
<Tags: Tags object>
It works for me, is not the model, is the Form, or the validator you are using
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With