Skip to content

Commit

Permalink
Tags added.
Browse files Browse the repository at this point in the history
  • Loading branch information
ShivamMenda committed Sep 20, 2023
1 parent e2c4bb3 commit 410089d
Show file tree
Hide file tree
Showing 6 changed files with 99 additions and 12 deletions.
1 change: 1 addition & 0 deletions app/core/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,5 @@ class UserAdminManager(UserAdmin):

admin.site.register(models.User,UserAdminManager)
admin.site.register(models.Recipe)
admin.site.register(models.Tag)

28 changes: 28 additions & 0 deletions app/core/migrations/0003_auto_20230920_1403.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Generated by Django 3.2.21 on 2023-09-20 14:03

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
('core', '0002_recipe'),
]

operations = [
migrations.CreateModel(
name='Tag',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddField(
model_name='recipe',
name='tag',
field=models.ManyToManyField(to='core.Tag'),
),
]
10 changes: 10 additions & 0 deletions app/core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,24 @@ class User(AbstractBaseUser,PermissionsMixin):

USERNAME_FIELD='email'

class Tag(models.Model):
"""Tag to be used for a recipe"""
name=models.CharField(max_length=255)
user=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)

def __str__(self):
return self.name

class Recipe(models.Model):
user= models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
title=models.CharField(max_length=255)
description=models.TextField(blank=True)
time_minutes=models.IntegerField()
price=models.DecimalField(max_digits=5, decimal_places=2)
link= models.CharField(max_length=255,blank=True)
tag=models.ManyToManyField('Tag')

def __str__(self):
return self.title


47 changes: 40 additions & 7 deletions app/recipe/serializers.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,46 @@
from rest_framework import serializers
from core.models import Recipe
from core.models import Recipe,Tag


class TagSerialzer(serializers.ModelSerializer):
class Meta:
model=Tag
fields=['id','name']
read_only_fields=['id']
class RecipeSerializer(serializers.ModelSerializer):
tags = TagSerialzer(many=True,required=False)
class Meta:
model=Recipe
fields=('id','title','price','link')
read_only_fields=('id',)
fields=['id','title','time_minutes','price','link','tags']
read_only_fields=['id']
def _get_or_create_tags(self,tags,recipe):
auth_user=self.context['request'].user
for tag in tags:
tag_obj,created=Tag.objects.get_or_create(user=auth_user,**tag)
recipe.tags.add(tag_obj)

class RecipeDetailSerializer(serializers.ModelSerializer):
class Meta:
model=Recipe
fields=('id','title','description','time_minutes','price','link')
def create(self, validated_data):
tags=validated_data.pop('tags',[])
recipe=Recipe.objects.create(**validated_data)
self._get_or_create_tags(tags,recipe)
return recipe
def update(self,instance,validated_data):
tags= validated_data.pop('tags',None)
if tags is not None:
instance.tags.clear()
self._get_or_create_tags(tags,instance)
for attr,value in validated_data.items():
setattr(instance,attr,value)
instance.save()
return instance



class RecipeDetailSerializer(RecipeSerializer):
"""Serializer for recipe detail view."""

class Meta(RecipeSerializer.Meta):
fields = RecipeSerializer.Meta.fields + ['description']



6 changes: 3 additions & 3 deletions app/recipe/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
from rest_framework.routers import DefaultRouter

router=DefaultRouter()
router.register('',views.RecipeViewSet)

router.register('recipes',views.RecipeViewSet)
router.register('tags',views.TagViewSet)

urlpatterns = [
path('recipes/',include(router.urls))
path('',include(router.urls))
]
19 changes: 17 additions & 2 deletions app/recipe/views.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from rest_framework import viewsets
from rest_framework import viewsets,mixins
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from core.models import Recipe
from core.models import Recipe,Tag
from recipe import serializers


Expand All @@ -25,5 +25,20 @@ def perform_create(self, serializer):
"""Create a new recipe for the current auth user"""
serializer.save(user=self.request.user)

# Generic viewset with mixins to reuse functionality
class TagViewSet(mixins.UpdateModelMixin,mixins.DestroyModelMixin,mixins.ListModelMixin,viewsets.GenericViewSet):
serializer_class=serializers.TagSerialzer
queryset=Tag.objects.all()
authentication_classes=[TokenAuthentication]
permission_classes=[IsAuthenticated]
def get_queryset(self):
"""Show only tags for the current auth user"""
return self.queryset.filter(user=self.request.user).order_by('-id')








0 comments on commit 410089d

Please sign in to comment.