I have a model i am trying to make a serializer out of however i cannot import the model into serializers.py. When i do i get this error:
ModuleNotFoundError: No module named 'airquality.air_quality'
This is the model i am trying to import
class Microcontrollers(models.Model):
name = models.CharField(max_length=25)
serial_number = models.CharField(max_length=20, blank=True, null=True)
type = models.CharField(max_length=15, blank=True, null=True)
software = models.CharField(max_length=20, blank=True, null=True)
version = models.CharField(max_length=5, blank=True, null=True)
date_installed = models.DateField(blank=True, null=True)
date_battery_last_replaced = models.DateField(blank=True, null=True)
source = models.CharField(max_length=10, blank=True, null=True)
friendly_name = models.CharField(max_length=45, blank=True, null=True)
private = models.BooleanField()
class Meta:
managed = True
db_table = 'microcontrollers'
verbose_name_plural = 'Microcontrollers'
def __str__(self):
return self.friendly_name
serializers.py
from rest_framework import serializers
from airquality.air_quality.models import Microcontrollers
class SourceStationsSerializer(serializers.ModelSerializer):
def create(self, validated_data):
pass
def update(self, instance, validated_data):
pass
class Meta:
model = Microcontrollers
fields = ['name']
The import is the one the IDE itself suggests i use when i type model = Microcontrollers in the serializer
use this if the model if the file in same directory
from .models import Microcontrollers
or if it is another directory wana import that model
from directoryname.models import Microcontrollers
Related
I have an Orders model, in which I didn't have slug field before. So I decided to add a slug field to it. But when I run makemigrations command it says 'No changes detected'. I've tried to manually create migration and run it, but it didn't affect my database.
Yes, I did check in settings, app is registered there.
Model:
class Orders(models.Model):
customer = models.ForeignKey('contractors.Customers',
models.DO_NOTHING, blank=True, null=True)
slug = models.SlugField(max_length=150, blank=True)
employee = models.ForeignKey('employees.Employees',
models.DO_NOTHING, blank=True, null=True)
order_date = models.DateField(blank=True, null=True, auto_now=True)
required_date = models.DateField(blank=True, null=True)
shipped_date = models.DateField(blank=True, null=True)
ship_via = models.ForeignKey('contractors.Shippers',
models.DO_NOTHING, db_column='ship_via',
blank=True, null=True)
freight = models.FloatField(blank=True, null=True)
ship_name = models.CharField(max_length=40, blank=True, null=True)
ship_address = models.CharField(max_length=60, blank=True, null=True)
ship_city = models.CharField(max_length=15, blank=True, null=True)
ship_region = models.CharField(max_length=15, blank=True, null=True)
ship_postal_code = models.CharField(max_length=10, blank=True, null=True)
ship_country = models.CharField(max_length=15, blank=True, null=True)
class Meta:
managed = False
db_table = 'orders'
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.customer + "-" + str(self.order_date))
super(Orders, self).save(*args, **kwargs)
def get_absolute_url(self):
return u'/orders/%d' % self.pk
def __str__(self):
return f"{self.customer} {self.order_date}"
My attempt to manually create migration:
# Generated by Django 3.2.7 on 2021-11-10 13:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('orders', '0008_alter_orderdetails_options'),
]
operations = [
migrations.AddField(
model_name='orders',
name='slug',
field=models.SlugField(max_length=150, blank=True),
preserve_default=False,
),
]
You have set managed = False in your model Meta. Django will not manage the model for you, see here. Set it to True if you want Django to manage migrations for you.
problem
class Meta:
managed = False
db_table = 'orders'
solution
class Meta:
db_table = 'orders'
I followed Dennis Ivy proshop Tutorial He used the same approach as the code is
class ReviewSerializer(serializers.ModelSerializer):
class Meta:
model = Review
fields = '__all__'
class ProductSerializer(serializers.ModelSerializer):
reviews = serializers.SerializerMethodField(read_only=True)
class Meta:
model = Product
fields = '__all__'
def get_reviews(self, obj):
reviews = obj.review_set.all()
serializer = ReviewSerializer(reviews, many=True)
return serializer.data
Now I need a Blog for the eCommerce Project and I created another app named blog and Created the models as
class BlogPost(models.Model):
_id = models.AutoField(primary_key=True, editable=False)
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
title = models.CharField(max_length=200, null=True, blank=True, help_text="Like How To Treat Hypertension etc")
image = models.ImageField(null=True, blank=True,
default='/placeholder.png')
rating = models.DecimalField(
max_digits=7, decimal_places=2, null=True, blank=True)
numReviews = models.IntegerField(null=True, blank=True, default=0)
createdAt = models.DateTimeField(auto_now_add=True)
youtubeVideoLink = models.CharField(max_length=1000, null=True , blank=True)
def __str__(self):
return str(self.createdAt)
class BlogPostReview(models.Model):
blogpost = models.ForeignKey(BlogPost, on_delete=models.SET_NULL, null=True)
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
name = models.CharField(max_length=200, null=True, blank=True)
rating = models.IntegerField(null=True, blank=True, default=0)
comment = models.TextField(null=True, blank=True)
createdAt = models.DateTimeField(auto_now_add=True)
_id = models.AutoField(primary_key=True, editable=False)
def __str__(self):
return str(self.rating)
But when I serialize them via same approach as mentioned above....
class BlogPostReviewSerializer(serializers.ModelSerializer):
class Meta:
model = BlogPostReview
fields = '__all__'
class BlogPostSerializer(serializers.ModelSerializer):
blog_post_reviews = serializers.SerializerMethodField(read_only=True)
class Meta:
model = BlogPost
fields = '__all__'
def get_blog_post_reviews(self, obj):
blog_post_reviews = obj.review_set.all()
serializer = BlogPostReviewSerializer(blog_post_reviews, many=True)
return serializer.data
This error comes
in get_blog_post_reviews
blog_post_reviews = obj.review_set.all()
AttributeError: 'BlogPost' object has no attribute 'review_set'
How to solve this problem or what I'm doing wrong and what need to be fixed. What would be another apporach obv there would be.... And I don't know why Dennis Ivy used review_set in his code. If someone know why we use _set and what are the circumstances please let me know.
The simplest solution is to update your get_blog_post_reviews method:
def get_blog_post_reviews(self, obj):
blog_post_reviews = obj.blogpostreview_set.all() # <- this line has changed
serializer = BlogPostReviewSerializer(blog_post_reviews, many=True)
return serializer.data
The original worked because there was a model named Review, so the automatically created reverse name was review_set. Your model is named BlogPostReview, so the reverse is blogpostreview_set.
More information about reverse relationships in the docs.
I'm having a problem with serializing the data with joined tables. Am i doing this right? i'm just a newbie in django.
here's my models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
class Agency(models.Model):
agency_id = models.CharField(primary_key=True, max_length=50)
agency_shortname = models.CharField(max_length=20, blank=True, null=True)
agency_longname = models.CharField(max_length=255, blank=True, null=True)
date_created = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'agency'
class Users(AbstractBaseUser):
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []
user_id = models.CharField(primary_key=True, max_length=50)
first_name = models.CharField(max_length=50, blank=True, null=True)
middle_name = models.CharField(max_length=50, blank=True, null=True)
last_name = models.CharField(max_length=50, blank=True, null=True)
username = models.CharField(unique=True, max_length=50, blank=True, null=True)
password = models.CharField(max_length=100, blank=True, null=True)
agency = models.OneToOneField(Agency, models.DO_NOTHING)
date_created = models.DateTimeField(blank=True, null=True)
active = models.CharField(max_length=8)
login_status = models.CharField(max_length=6)
last_login = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'users'
Then in my serializers.py
from rest_framework import serializers
from .models import Users, Agency
class UserDetailSerializer(serializers.ModelSerializer):
class Meta:
model = Users
fields = '__all__'
class AgencyDetailSerializer(serializers.ModelSerializer):
agency_id = UserDetailSerializer()
class Meta:
model = Agency
fields = ['agency_id','agency_shortname','agency_longname']
and my views.py
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from .serializers import UserDetailSerializer
from .models import Users, Agency
from rest_framework.permissions import IsAuthenticated
#api_view(['GET'])
#permission_classes([IsAuthenticated])
def userData(request):
username = request.GET.get('username')
r_type = request.GET.get('type')
user = Users.objects.get(username=username).values('user_id','first_name','middle_name','last_name','username','email','agency__agency_id','agency__agency_shortname','agency__agency_longname')
user_serializer = UserDetailSerializer(user, many=False)
return Response(user_serializer.data)
I'm getting an error of 'Users' object has no attribute 'values', what seems be the problem? i'm building api based application with vue.js and django rest framework. Thanks a lot
get queryset does not have values attribute, using filter instead.
user = Users.objects.filter(username=username).values(...)
Regarding your case, using get is enough and custom your Serializer like this:
class UserDetailSerializer(serializers.ModelSerializer):
class Meta:
model = Users
fields = '__all__'
agency = AgencyDetailSerializer(many=False, read_only=True)
Because values is not an attribute of model object. You can call values on queryset object. something like:
user = Users.objects.filter(username=username).values('user_id','first_name','middle_name','last_name','username','email','agency__agency_id','agency__agency_shortname','agency__agency_longname')
Note: You don't need to call values, just change this line to:
from rest_framework.generics import get_object_or_404
...
user = get_object_or_404(Users, **dict(username=username))
user_serializer = UserDetailSerializer(user)
...
Because serializer itself will handle it for you.
I want to add items from Available classic to Chosen classic
how can i do that as in image below
i can get Chosen classic by
Profile.objects.get(user=request.user).classic.add(id=2)
but i can't add iems from Available classic to Chosen classic
any one can help this problem fast please
Thanks for all
Models.py
from django.db import models
# Create your models here.
from django.utils import timezone
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Language(models.Model):
language = models.CharField(
max_length=2,
choices=[
('AR', 'Arabic'),
('EN', 'English'),
],
default='AR'
)
def __str__(self):
return self.language
class Classic(models.Model):
name = models.CharField(max_length=50, blank=False, null=False)
music = models.FileField(upload_to='', max_length=100, blank=True, null=True)
lang = models.ForeignKey(Language, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
classic = models.ManyToManyField(Classic, blank=True, null=True)
workOut = models.ManyToManyField(WorkOut, blank=True, null=True)
chillOut = models.ManyToManyField(ChillOut, blank=True, null=True)
romantic = models.ManyToManyField(Romantic, blank=True, null=True)
happy = models.ManyToManyField(Happy, blank=True, null=True)
sad = models.ManyToManyField(Sad, blank=True, null=True)
lang = models.ManyToManyField(Language, blank=True, null=True)
def __str__(self):
return str(self.user)
def update_user_profile(sender, **kwargs):
if kwargs['created']:
user = Profile.objects.create(user=kwargs['instance'])
post_save.connect(update_user_profile,sender=User)
Admin.py
from django.contrib import admin
# Register your models here.
from . import models
class ClassicAdmin(admin.TabularInline):
model = models.Classic
class PlayLists(admin.ModelAdmin):
inlines = [ClassicAdmin]
class Favo(admin.ModelAdmin):
filter_horizontal = ['classic']
admin.site.register(models.Language, PlayLists)
admin.site.register(models.Profile, Favo)
what's wrong with in my code
thank for all
Thant's works with me
Profile.objects.get(user=request.user).classic.add(Classic.objects.get(id=1))
I've an app called lists.
This has 3 main models: List, ListItem and School.
Every list could be related to 1 school, or this field could be empty.
But when I'm trying to update my model List to have a school field I'm getting:
ImportError: cannot import name 'School' from 'lists.models' (D:\web_proyects\scolarte\lists\models.py)
(scolarte)
Even thought both models are in the same models.py file.
I've tried:
from .models import School
And:
from lists.models import School
lists/models.py:
from django.db import models
from products.models import Product
from roles.models import User
from .models import School
# Create your models here.
class List(models.Model):
LISTA_STATUS = (
('recibida_pagada', 'Recibida y pagada'),
('recibida_no_pagada', 'Recibida pero no pagada'),
('en_revision', 'En revision'),
('en_camino', 'En camino'),
('entregada', 'Entregada'),
('cancelada', 'Cancelada')
)
lista_id = models.CharField(max_length=100)
name = models.CharField(max_length=100)
user = models.OneToOneField(User, on_delete=models.CASCADE)
school = models.OneToOneField(School, on_delete=models.CASCADE)
status = models.CharField(max_length=20, choices=LISTA_STATUS, default='recibida_pagada')
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['created_at']
def __str__(self):
return str(self.id)
class ListItem(models.Model):
lista = models.ForeignKey(List, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
comment = models.CharField(max_length=100, blank=True, null=True, default='')
uploaded_at = models.DateTimeField(auto_now_add=True)
step_two_complete = models.BooleanField(default=False)
def sub_total(self):
return int(self.product.price)
class School(models.Model):
name = models.CharField(max_length=100)
address = models.CharField(max_length=100, blank=False)
address_reference = models.CharField(max_length=100, blank=False)
provincia = models.CharField(max_length=100, blank=False, null=True)
canton = models.CharField(max_length=100, blank=False, null=True)
parroquia = models.CharField(max_length=100, blank=False, null=True)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['created_at']
def __str__(self):
return str(self.name)
You don't need to import School since its already in the same model. However you do need to define School first before you can then reference it in another class in the same model file. Update your model so School is defined before List
from django.db import models
from products.models import Product
from roles.models import User
from .models import School
# Create your models here.
class School(models.Model):
name = models.CharField(max_length=100)
address = models.CharField(max_length=100, blank=False)
address_reference = models.CharField(max_length=100, blank=False)
provincia = models.CharField(max_length=100, blank=False, null=True)
canton = models.CharField(max_length=100, blank=False, null=True)
parroquia = models.CharField(max_length=100, blank=False, null=True)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['created_at']
def __str__(self):
return str(self.name)
class List(models.Model):
LISTA_STATUS = (
('recibida_pagada', 'Recibida y pagada'),
('recibida_no_pagada', 'Recibida pero no pagada'),
('en_revision', 'En revision'),
('en_camino', 'En camino'),
('entregada', 'Entregada'),
('cancelada', 'Cancelada')
)
lista_id = models.CharField(max_length=100)
name = models.CharField(max_length=100)
user = models.OneToOneField(User, on_delete=models.CASCADE)
school = models.OneToOneField(School, on_delete=models.CASCADE)
status = models.CharField(max_length=20, choices=LISTA_STATUS, default='recibida_pagada')
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['created_at']
def __str__(self):
return str(self.id)
class ListItem(models.Model):
lista = models.ForeignKey(List, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
comment = models.CharField(max_length=100, blank=True, null=True, default='')
uploaded_at = models.DateTimeField(auto_now_add=True)
step_two_complete = models.BooleanField(default=False)
def sub_total(self):
return int(self.product.price)