I'm in the process of creating an application for a personal project I'm working on that involves Python 3, peewee, and (for the moment) Sqlite3. In main, I'm importing a 2 model classes (student and course) which are subclasses of a basemodel class I create.
The import statements located in main.py:
from models.course import Course
from models.student import Student
The models/BaseModel.py
from peewee import *
db = SqliteDatabase('database/attendance.db')
class BaseModel:
class Meta:
database = db
The models/course.py
from peewee import *
from models.basemodel import BaseModel
class Course(BaseModel):
cid = PrimaryKeyField()
title = TextField()
active = BooleanField()
class Meta:
table_name = 'courses'
When I try to do a simply query to retrieve courses, I receive an error message.
Example query:
active_courses = Course.select().where(Course.active == True)
The error message I receive is:
AttributeError: type object 'Course' has no attribute 'select'
Your BaseModel class needs to extend peewee.Model:
class BaseModel(peewee.Model):
...
Related
I want to add a class-based view to return users created from one date to another date. I have tried the following are there other ways to filter the user-created between two dates?
While doing this I get:
TypeError: get() missing 1 required positional argument: 'to_date'
views.py
class RegisteredUserFilter(APIView):
serializer = RegisteredUserFilterSerializer
def get(self, from_date, to_date):
userondate = User.objects.filter(created_at__range=[from_date, to_date]).values()
return Response({"User": userondate})
serializers.py
class RegisteredUserFilterSerializer(serializers.Serializer):
from_date = serializers.DateField()
to_date = serializers.DateField()
model = User
full code at: https://github.com/abinashkarki/rest_framework_authentication/tree/master/authapp
using Django filters
serilaizers.py
add the following
class RegisteredUserFilterSerializer(serializers.Serializer):
class Meta:
model = User
fields = ['username', 'created_at']
make file name it filters.py in same path of views.py
filters.py
from django_filters.rest_framework import FilterSet
import django_filters
from .models import User
from django_filters.widgets import RangeWidget
class UserFilter(FilterSet):
date_range = django_filters.DateFromToRangeFilter(label='Date Range', field_name='created_at',
widget=RangeWidget(attrs={'type': 'date'}))
class Meta:
model = User
fields = ['created_at']
Views.py
from .serializers import RegisteredUserFilterSerializer
from .filters import UserFilter
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.generics import ListAPIView
class RegisteredUserFilter(ListAPIView):
serializer_class = RegisteredUserFilterSerializer
filter_backends = [DjangoFilterBackend]
filterset_class = UserFilter
model = User
urls.py add
from django.urls import path
from .views import RegisteredUserFilter
urlpatterns = [
path('users-filter/', RegisteredUserFilter.as_view(), name="user-filter"),
]
finally do not forget to make
pip install django-filter
and add it to installed app in settings.py
INSTALLED_APPS = [
...
'django_filters',
]
for more information refer to https://django-filter.readthedocs.io/en/stable/guide/rest_framework.html
another approach
you can make this process manually by overriding the get method and getting query parameters manually
and return response after serializing the query set
I am trying to use timezone_field, but it shows it is not serializable and shows error.
Please need your help. I have provided code in below..
Thanks in advance.
Models.py
from django.db import models
from timezone_field import TimeZoneField
# Create your models here.
class Member(models.Model):
tz = TimeZoneField(default='Asia/Kolkata')
def __str__(self):
return self.tz
serializers.py
from . models import Member
from rest_framework.serializers import ModelSerializer
class Member_Serializer(ModelSerializer):
class Meta:
model = Member
fields = '__all__'
views.py
from . models import Member
from . serializers import Member_Serializer
from rest_framework.generics import ListCreateAPIView
# Create your views here.
class MemberListView(ListCreateAPIView):
queryset = Member.objects.all()
serializer_class = Member_Serializer
error:
Object of type Asia/Kolkata is not JSON serializable
Request Method: POST
Request URL: http://localhost:8000/a/
Django Version: 3.1.1
Exception Type: TypeError
Exception Value:
Object of type Asia/Kolkata is not JSON serializable
You need to specify the serialization behaviour for the tz field
from .models import Member
from rest_framework import serializers
class Member_Serializer(serializers.ModelSerializer):
tz = serializers.CharField()
class Meta:
model = Member
fields = '__all__'
I have model Product with field MoneyField in /products/models.py
class Product(SeoModel, ModelWithMetadata, PublishableModel):
name = models.CharField(max_length=128)
currency = models.CharField(
max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
default=settings.DEFAULT_CURRENCY,
)
price_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
)
price = MoneyField(amount_field="price_amount", currency_field="currency")
My views.py is:
from .models import Product
from .serializers import ProductListSerializer
from rest_framework import generics
class ProductList(generics.ListAPIView):
queryset = Product.objects.all()
serializer_class = ProductListSerializer
and serializers.py:
from rest_framework import serializers
from .models import Product
class ProductListSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ['name', 'id']
and when i go to url i have error:
AttributeError at /ru/products/api/
'MoneyField' object has no attribute 'serialize'
Request Method: GET
Request URL: http://127.0.0.1:8000/ru/products/api/
Django Version: 2.2.6
Exception Type: AttributeError
Exception Value:
'MoneyField' object has no attribute 'serialize'
Can you help me? Thank you!
DRF's ModelSerializer assumes fields that are on the model extend django.db.models.fields.Field, which MoneyField does not. This is a problem when ModelSerializer is collecting fields:
# rest_framework.utils.model_meta._get_fields
def _get_fields(opts):
fields = OrderedDict()
for field in [field for field in opts.fields if field.serialize and not field.remote_field]:
fields[field.name] = field
return fields
You can fix the problem by subclassing MoneyField:
from django_prices.models import MoneyField as BaseMoneyField
class MoneyField(BaseMoneyField):
serialize = True
This will probably lead to your next problem ;)
I'm having some trouble getting relationships fields to work in umongo. Each Document definition is in a separate file.
In this example i have two basic entities, account and target.
each target has a reference to an account.
// account/schema.py
from datetime import datetime
from pymongo import MongoClient
from umongo import Instance, Document, fields, validate
import os
log = Config.config_logger(__name__)
mongo_url = os.environ.get('MONGO_URL')
db = MongoClient(mongo_url).mydb
instance = Instance(db)
#instance.register
class AccountSchema(Document):
user_id = fields.StringField(required=True, unique=True)
user_name = fields.StringField(required=True)
account_type = fields.StringField(required=True)
class Meta:
collection = db.account
# Make sure that unique indexes are created
AccountSchema.ensure_indexes()
try:
sub = AccountSchema(user_id='my8htwwi', account_type='SUBSCRIPTION', user_name='myuser')
sub.commit()
freeloader = AccountSchema(user_id='ouygouyg', account_type='FREE', user_name='myotheruser')
freeloader.commit()
except Exception:
log.info('account already created')
I've added some manual data there at the bottom, and that works fine when I execute this file, or import it elsewhere.
I define second entity schema for 'target'
// target/schema.py
from datetime import datetime
from pymongo import MongoClient
from umongo import Instance, Document, fields, validate
import os
mongo_url = os.environ.get('MONGO_URL')
db = MongoClient(mongo_url).mydb
instance = Instance(db)
#instance.register
class TargetSchema(Document):
account = fields.ReferenceField('AccountSchema', required=True)
date = fields.DateTimeField(
default=lambda: datetime.utcnow(),
allow_none=False
)
somefield = fields.IntegerField(required=True)
value = fields.IntegerField(required=True)
class Meta:
collection = db.target
# Make sure that unique indexes are created
TargetSchema.ensure_indexes()
service.py
from models.account.schema import AccountSchema
from models.target.schema import TargetSchema
class Service:
self._odm = TargetSchema
....
def save_test(data):
account = AccountRepo().find({'user_id': self._user_id})
# account returns a valid object
item = self._odm(
account=account,
somefield=123123,
value=1234
)
return item.commit()
When I call save_test method, I keep keep getting:
umongo.exceptions.NotRegisteredDocumentError: Unknown document class `AccountSchema`
I get the same error if i try and pass the class object AccountSchema in instead
from models.account.schema import AccountSchema
#instance.register
class TargetSchema(Document):
account = fields.ReferenceField(AccountSchema, required=True)
my feeling is it's about the order that I instantiate/import the instances, but trying to move them around, for example into __init__.py, doesn't seem to change anything.
Or how in each schema definition:
db = MongoClient(mongo_url).target
instance = Instance(db)
All examples I've been able to find keep the referencefield class definition in the same file, so I'm not really sure how to make the different registered instances 'aware' of each other.
so the issue was not declaring and registering all classes to the same db instance.
i.e. in the __init__.py for the models folder i moved:
from umongo import Instance, Document, fields, validate
from pymongo import MongoClient
db = MongoClient(mongo_url).mydb
instance = Instance(db)
then in each schema file:
from models import db
from models import instance
This is my first experience with Graphene, I suppose my question is so obvious...
But when I am Testing GraphQL schema in this step-by-step tutorial on last step it throws a TypeError: '<' not supported between instances of 'String' and 'NoneType'
Where I am wrong?
All the previous steps are ok.
try this for schema.py
import graphene
from graphene_sqlalchemy import SQLAlchemyObjectType
from models import (
Department as DepartmentModel,
Employee as EmployeeModel,
)
class Department(SQLAlchemyObjectType):
class Meta:
model = DepartmentModel
class Employee(SQLAlchemyObjectType):
class Meta:
model = EmployeeModel
class Query(graphene.ObjectType):
all_employees = graphene.List(Employee)
all_departments = graphene.List(Department)
def resolve_employees(self, info):
query = Employee.get_query(info)
return query.all()
def resolve_departments(self, info):
query = Department.get_query(info)
return query.all()
schema = graphene.Schema(query=Query)