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
Related
Read:How to upload multiple files in django rest framework
read:django rest framework for multiple image upload
But still unable to follow as proper description is not given
hi,
i am creating a rest api and new to django rest framework. I need help with few points mentioned below:
How to create Foreign key correctly.I have two tables one where images will be uploaded and one where data will be saved, i want id of these two tables should be foreign key so that when i select data from table 1 i can make query and get images related to id of table 1 from images table
I have created serializers but they say when i run my code to check errors using serializers.error
{'image': ['Incorrect type. Expected pk value, received bytes.'], 'img_id':
['Invalid pk "1" - object does not exist.']}
I am writing a post api to i need to save data and images first
How can i achieve this
my code
models
from django.db import models
# Create your models here.
class ImageModels(models.Model):
media = models.ImageField(upload_to="images")
class categoryRegistration(models.Model):
name = models.CharField(max_length=100)
image=models.ManyToManyField(ImageModels,related_name="file_content",blank=True,null=True)
description = models.TextField()
price = models.IntegerField()
img_id = models.ForeignKey(ImageModels,on_delete=models.CASCADE)
serializer
from rest_framework import serializers
from apps.categorymanagement.models import categoryRegistration
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = categoryRegistration
fields = ("id",'name', 'image', 'description', 'price',"img_id")
extra_kwargs = {
"image":{
"required":False,
},
}
urls:
from django.conf.urls import url
from apps.categorymanagement import views
urlpatterns = [
url( r'^object/categories$',views.category_list ,name="categoryList"),
url( r'^categories/data/(?P<pk>[0-9]+)$',views.category_detail,name="categoryDetails" ),
url( r'^categories/released$',views.category_released,name="categoryReleased" )
]
views:
from django.http.response import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework.response import Response
from rest_framework import status
from apps.categorymanagement.models import ImageModels, categoryRegistration
from apps.categorymanagement.serializers import CategorySerializer
from rest_framework.decorators import api_view
# all the views written here are fuctions based
#api_view(['GET','POST','DELETE'])
def category_list(request):
# get list of all categories
if request.method=="POST":
files = request.FILES.getlist("file_content")
form_data = {}
form_data["name"] = request.data["name"]
form_data["description"] = request.data["description"]
form_data["price"] = request.data["price"]
form_data["img_id"] = request.data["img_id"]
for images in files:
form_data["image"] = images
serializer = CategorySerializer(data=form_data)
print(serializer.is_valid())
print(serializer.errors)
return Response('ok')
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'm creating a basic flask web application and want to get some data from my mongo database. In my views.py I have that:
from app import app
from app.models import User
#app.route('/')
def index():
return "Hello world"
#app.route("/users")
def about():
users = User.objects()
return users.to_json()
models.py:
from flask_mongoengine import MongoEngine
from app import db
class User(db.Document):
snp = db.StringField(required=False)
g = db.StringField(required=False)
card = db.StringField(required=False)
phone = db.StringField(required=False)
passport = db.StringField(required=False)
group = db.StringField(required=False)
meta = {'collection': 'User'}
def to_json(self):
return {
"name": self.snp
}
When I enter http://127.0.0.1:5000/users I get []. Find returns nothing but in my mongo database I have collection User with two document:
{"_id":{"$oid":"6089d5d13dc15d0a2c5f607e"},"snp":"testov1 test1 testovich1","g":"f","card":"12345","phone":"8888888881","passport":"8888 48484848","group":"users"}
and
{"_id":{"$oid":"6089d5fd3dc15d0a2c5f607f"},"snp":"testov2 test2 testovich2","g":"m","card":"1676767","phone":"88566768881","passport":"8888 234343434","group":"users"}
Connection to database is correct.
I'm new to flask and mongoEngine.
If you print users, you will see a list of 'User' objects, Actually When you try to get all users with User.objects() , the result is of type <class 'flask_mongoengine.BaseQuerySet'>, so calling users.to_json() is wrong since it is not an instance of class User .
But if you get only one user with something like User.objects().first(), the result would be of type "User", and then you can call user.to_json().
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):
...
I would really appreciate if someone can help me with this. I need Django (Python) function to inject some parameters into a pipeline script, pass it to MongoDB Atlas and receive the result in a cursor.
from bson import ObjectId
import pymongo
conn = "connection string"
client = pymongo.MongoClient(conn)
pipeline = [
<<pipeline script>>
]
out = client.db.mycollection.aggregate(pipeline)
If you're using Djongo to connect the Django ORM to MongoDB, you could use the provided DjongoManager as the manager for your Model, and use PyMongo functions using the mongo_ prefix. Here's a quick example:
models.py
from djongo import models
class Message(models.Model):
text = models.CharField(max_length=150)
objects = models.DjongoManager()
Then in the shell you could do something like:
>>> from core.models import *
>>> cursor = Message.objects.mongo_aggregate('pipeline')