Problem
I want to create Student With Address. How can I write REST API in Django for same.
Address & Student
class Address(models.Model):
address = models.CharField(max_length=100, null=False, blank=False)
land_mark = models.CharField(max_length=100, null=True, blank=True)
city = models.CharField(max_length=100, null=True, blank=True)
state = models.CharField(max_length=100, null=True, blank=True)
pin_code = models.CharField(max_length=100, null=True, blank=True)
latitude = models.FloatField(default=0.0)
longitude = models.FloatField(default=0.0)
geo_code = models.CharField(max_length=100, null=True, blank=True)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE,
null=True)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
class Student(models.Model):
name = model.CharField(max_length=100, null=False, blank=False)
address = GenericRelation(Address)
def __str__(self):
return self.name
Serializers
class AddressSerializer(serializers.ModelSerializer):
class Meta:
model = Address
fields = "__all__"
class StuddentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = "__all__"
API View
class AddressApiView(ListCreateAPIView):
queryset = Address.objects.all()
serializer_class = AddressSerializer
class StudentApiView(ListCreateAPIView):
queryset = Student.objects.all()
serializer_class = StuddentSerializer
How do I get my create/view student?
You can try with third-party app rest-framework-generic-relation link
Related
Excuse me devs, i wanna ask about how to count on drf serializer, i need codes that can serialized fields plant from table A and it relations with another table B with count of them "plants_active"
Here's my code:
# Models
class TablePlants(models.Model):
plant_id = models.CharField(primary_key=True, max_length=20, unique=True)
gateway = models.ForeignKey(
TableGatewayDevice, models.DO_NOTHING, blank=True, null=True)
name = models.CharField(max_length=150, blank=True, null=True)
date = models.DateField(blank=True, null=True)
contact_person = models.CharField(max_length=70, blank=True, null=True)
contact_email = models.CharField(max_length=50, blank=True, null=True)
contact_phone = models.CharField(max_length=30, blank=True, null=True)
plant_status = models.CharField(max_length=20, blank=True, null=True)
weather_status_code = models.ForeignKey(
TableAuxWeather, models.DO_NOTHING, db_column='weather_status_code', blank=True, null=True)
timezone = models.CharField(max_length=200, blank=True, null=True)
image = models.FileField(
upload_to='plants/', validators=[file_size, validate_file_extension], null=True, blank=True)
class Meta:
db_table = 'table_plants'
def __str__(self):
return 'TablePlants[id: {id}, name: {name}]'.format(
id=self.id, name=self.name)
class PVOwner(models.Model):
pv_owner_id = models.AutoField(primary_key=True)
company = models.ForeignKey(TableCompany, on_delete=CASCADE,
blank=True, null=True, related_name="pv_owner_company")
class Meta:
db_table = 'table_pv_owner'
class TableSitePlant(models.Model):
pv_owner = models.ForeignKey(
PVOwner, on_delete=CASCADE, blank=True, null=True, related_name="pv_site_owner_plant")
site_owner = models.ForeignKey(
SiteOwner, on_delete=CASCADE, blank=True, null=True, related_name="site_owner_plant")
plant = models.ForeignKey(TablePlants, on_delete=CASCADE,
blank=True, null=True, related_name="site_plant")
class Meta:
db_table = 'table_site_plant'
# Serializer
class MainMenuSerializer(serializers.ModelSerializer):
plants_active = serializers.IntegerField(source="plant")
class Meta:
model = TableSitePlant
fields = ['plants_active']
# Views
#permission_classes([AllowAny])
class OverviewPlantsActiveView(generics.RetrieveAPIView):
queryset = TableSitePlant.objects.all().filter(plant__plant_status='offline')
serializer_class = OverviewPlantsActiveSerializer
lookup_field = 'pv_owner'
What i expecting is i can count how many plants that have status online
You can use the get method to return response as you desired.
#permission_classes([AllowAny])
class OverviewPlantsActiveView(generics.RetrieveAPIView):
queryset = TableSitePlant.objects.all().filter()
serializer_class = OverviewPlantsActiveSerializer
lookup_field = 'pv_owner'
def get(self, request):
queryset = self.get_queryset().filter(plant__plant_status='online')
return Response({
"active_plants": queryset.count(),
})
I am creating a minimal viable product of a recipe application. I would like to leverage the admin site to create a diary entry that, consists of a recipe, that consists of ingredients with amounts and quantities. I read that inlines are possible. However, I have not successfully been able to implement one.
class Meal(models.Model):
id = models.BigAutoField(primary_key=True, editable=False)
name = models.CharField(max_length=64, unique=True)
class Meta:
verbose_name = ("Meal")
verbose_name_plural = ("Meals")
def __str__(self):
return f"{self.name}"
class Measurement(models.Model):
id = models.BigAutoField(primary_key=True, editable=False)
name = models.CharField(max_length=64, unique=True)
class Meta:
verbose_name = ("Measurement")
verbose_name_plural = ("Measurements")
def __str__(self):
return f"{self.name}"
class Ingredient(models.Model):
id = models.BigAutoField(primary_key=True, editable=False)
name = models.CharField(max_length=64, unique=True)
class Meta:
verbose_name = ("Ingredient")
verbose_name_plural = ("Ingredients")
def __str__(self):
return f"{self.name}"
class Recipe(models.Model):
id = models.BigAutoField(primary_key=True, editable=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=64)
class Meta:
verbose_name = ("Recipe")
verbose_name_plural = ("Recipes")
def __str__(self):
return f"{self.name}"
class RecipeIngredient(models.Model):
id = models.BigAutoField(primary_key=True, editable=False)
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
quantity = models.CharField(max_length=64, blank=True, null=True)
measurement = models.ForeignKey(Measurement, on_delete=models.CASCADE, blank=True, null=True)
ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE)
class Meta:
verbose_name = ("RecipeIngredient")
verbose_name_plural = ("RecipeIngredients")
class Diary(models.Model):
id = models.BigAutoField(primary_key=True, editable=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
occured_at = models.DateTimeField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
class Meta:
verbose_name = ("Diary")
verbose_name_plural = ("Diaries")
According to your requirement, you can use StackedInline or TabularInline. Here is the code for general StackedInline. TabularInline works in the same way.
#admin.py
class Class_1(admin.StackedInline):
model = Model_1
class Class_2(admin.StackedInline):
model = Model_2
class Class_3(admin.ModelAdmin):
inlines = [Class_1,Model_2]
admin.site.register(Model_Name, Class_3)
I have a models like this:
class Author(models.Model):
name = models.CharField(max_length=150, blank=False, null=False)
dob = models.DateField(null=True, blank=True)
description = models.TextField(max_length=2000, blank=False, default="This author doesn't have any description yet!")
image = models.ImageField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['created']
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=200, blank=False, null=False)
author = models.CharField(max_length=200)
genres = models.ManyToManyField(Genre, related_name='genre', blank=True)
author = models.ForeignKey(Author, related_name='author', blank=True, on_delete=models.CASCADE)
description = models.TextField(max_length=1200, blank=False, default="This book doesn't have description yet!")
image = models.ImageField(default="")
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['created']
def __str__(self):
return self.title
class Review(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
book = models.ForeignKey(Book, on_delete=models.CASCADE)
title = models.CharField(max_length=100, null=False, blank=False, help_text="Title overall of your review")
rating = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(5)], help_text='Rating in range 0-5')
description = models.TextField(max_length=1000, null=False, blank=False)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
I want to get Book data response in json with my reviews of the book from my Review table but don't know how. I am not getting any useful solution from documentation and Google, please help.
You could set the related_name field in the book field of the Review model.
class Review(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name = 'reviews')
...
Then in the serializer, you can add the related field.
class ReviewSerializer(serializers.ModelSerializer):
class Meta:
model = Review
fields = '__all__'
class BookSerializer(serializers.ModelSerializer):
reviews = ReviewSerializer(many = True)
class Meta:
model = Book
fields = '__all__'
extra_fields = ('reviews', )
I have model named organization. I am using this same model model for 2 api's. I have a field code. one API do code auto generation another API takes user entry code. I want to separate the tables based on code. Autogeneration code starts SUB001,SUB002,.... like wise. user entry code thats userwish.
models.py
class Organization(models.Model):
code = models.CharField(max_length=255, null=False, unique=True)
name = models.CharField(max_length=255, null=False)
organization_type = models.CharField(max_length=255, choices=TYPES, null=False, default=COMPANY)
internal_organization = models.BooleanField(null=False, default=True)
location = models.ForeignKey(Location, on_delete=models.RESTRICT)
mol_number = models.CharField(max_length=255, null=True, blank=True)
corporate_id = models.CharField(max_length=255, null=True, blank=True)
corporate_name = models.CharField(max_length=255, null=True, blank=True)
routing_code = models.CharField(max_length=255, null=True, blank=True)
iban = models.CharField(max_length=255, null=True, blank=True)
description = models.TextField(null=True, blank=True)
total_of_visas = models.IntegerField(null=False, default=0)
base_currency = models.ForeignKey(Currency, on_delete=models.RESTRICT, null=True, blank=True, default=None)
logo_filename = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True)
def __str__(self):
return self.name
admin.py
#admin.register(Organization)
class OrganizationAdmin(admin.ModelAdmin):
list_display = (
'id',
'code',
'name',
'location',
'organization_type',
'internal_organization',
'mol_number',
'corporate_id',
'corporate_name',
'routing_code',
'iban',
'description',
'total_of_visas',
'base_currency',
'logo_filename',
)
Is there any possible to split models based on code,.. Really Expecting help...
You can use Proxymodel inheritance. Documentation
class AutoGenerationManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(code__istartswith="SUB")
class AutoGeneration(Organization):
objects = AutoGenerationManager()
class Meta:
proxy = True
class UserGenerationManager(models.Manager):
def get_queryset(self):
return super().get_queryset().exclude(code__istartswith="SUB")
class UserGeneration(Organization):
objects = UserGenerationManager()
class Meta:
proxy = True
I'm creaating an api that user can create a job. when I want to test it with postman and create a job I have this error:
IntegrityError at /job/create/
NOT NULL constraint failed: core_job.category_id
how do i can fix it ?? I'm using generic CreateAPIView
models:
class Category(models.Model):
name = models.CharField(max_length=300)
slug = models.SlugField(max_length=300, unique=True, help_text='write in English.')
sub_category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE)
class Job(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
name = models.CharField(max_length=400, unique=True)
slug = models.SlugField(max_length=400, unique=True, allow_unicode=True)
category = models.ForeignKey(Category, on_delete=models.DO_NOTHING)
image_1 = models.ImageField(upload_to='products_pic/%Y/%m/%d/', null=True, blank=True)
description = models.TextField(null=True, blank=True)
phone1 = models.CharField(max_length=12, null=True, blank=True)
phone2 = models.CharField(max_length=12, null=True, blank=True)
phase = models.CharField(max_length=1, null=True, blank=True)
address = models.TextField(null=True, blank=True)
daily_start_work_time = models.TimeField(null=True, blank=True)
daily_end_work_time = models.TimeField(null=True, blank=True)
create_date = models.DateTimeField(auto_now_add=True)
update_date = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=False)
popular = models.BooleanField(default=False)
views:
class JobCreateView(generics.CreateAPIView):
permission_classes = (IsAuthenticated,)
serializer_class = JobSerializer
queryset = Job.objects.all()
serializers:
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = '__all__'
class JobSerializer(serializers.ModelSerializer):
category = serializers.SerializerMethodField()
class Meta:
model = Job
fields = '__all__'
lookup_field = 'slug'
extra_kwargs = {
'url': {'lookup_field': 'slug'}
}
def get_category(self, obj):
return obj.category.name
The category field is not populating with any value when you create the job. I mean category field is Null when you save that form. I am not sure but any way the problem is related to category field