Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Many to Many field blank=True on both sides in django

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)),
]
like image 952
Mike Dudnik Avatar asked Dec 02 '15 17:12

Mike Dudnik


2 Answers

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!

like image 174
Mike Dudnik Avatar answered Nov 14 '22 23:11

Mike Dudnik


>>> 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

like image 43
Zartch Avatar answered Nov 14 '22 22:11

Zartch