What is the best way to save comma separated keywords posted from client side into database table using Django?

42 views Asked by At

I have a text area input on a simple HTML page, where I am posting comma-separated keywords to save into my database table. For example, Keywords input is like: keyword1,keyword2,keyword3, ...

enter image description here

I am using Django 3.2 and Tastypie as a API framework.

Here is my Django model:

class Keywords(models.Model):
    keyword = models.CharField(max_length=200, unique=True)
    
    class Meta:
        db_table = 'keywords'

And Tastypie resource:

class KeywordResource(ModelResource):
    class Meta(CommonMeta):
        queryset = Keywords.objects.all()
        resource_name = 'keyword-resource'
        filtering = {'id': ALL, 'keyword': ALL}
        allowed_methods = ['get', 'post', 'put', 'patch']

I want to save the comma-separated keyword in one post request from the client side. How can I post comma-separated keywords and insert them one by one into the table Keywords? Also, what would be the best way to use save() method from model or hydrate() method from tastypie resource to prepare the data to save?

1

There are 1 answers

2
Dante On

you can override the hydrate and the obj_create method


from tastypie.authorization import Authorization

class KeywordResource(ModelResource):
    class Meta(CommonMeta):
        queryset = Keywords.objects.all()
        resource_name = 'keyword-resource'
        filtering = {'id': ALL, 'keyword': ALL}
        allowed_methods = ['get', 'post', 'put', 'patch']
        authorization = Authorization()

    def hydrate(self, bundle):
        # Retrieve the comma-separated keywords from the input data
        keywords = bundle.data.get('keywords', '')  # Assuming the input field is named 'keywords'
        
        # Split the keywords, remove leading/trailing whitespace, and create a list
        keyword_list = [kw.strip() for kw in keywords.split(',') if kw.strip()]
        
        # Update the 'keywords' field in the bundle data with the processed list
        bundle.data['keywords'] = keyword_list
        
        return bundle

    def obj_create(self, bundle, **kwargs):
        # Retrieve the list of keywords from the bundle data
        keyword_list = bundle.data.get('keywords')
        
        # Loop through each keyword and create or retrieve it in the 'Keywords' table
        for keyword in keyword_list:
            keyword_obj, created = Keywords.objects.get_or_create(keyword=keyword)
        
        return bundle