I am creating an app in which I have a User entity and an Item entity that are related one to many.
I am using TORTOISE ORM, in a file with the path: app/models/user.py I have the following code:
from tortoise import fields
from app.models.base_class import Base
class User(Base):
name = fields.CharField(max_length = 50, nullable = False)
last_name = fields.CharField(max_length = 50, nullable = False)
email = fields.CharField(max_length = 128, unique = True, nullable = False)
password = fields.CharField(max_length = 128, nullable = False)
create_date = fields.DatetimeField(auto_now = True)
class Meta:
table = 'user_db'
Hello, I am creating an app in which I have a User entity and an Item entity that are related one to many.
I am using TORTOISE ORM, in a file with the path: app/models/user.py I have the following code:
And in the path: app/models/item.py I have the following code:
from tortoise.models import Model
from tortoise import fields
from app.models.base_class import Base
class Item(Base):
title = fields.CharField(max_length = 50, nullable = False)
description = fields.TextField(nullable = False)
weight = fields.DecimalField(max_digits=3)
cost = fields.DecimalField(max_digits=3)
url_image = fields.CharField(max_length = 255)
user_id = fields.ForeignKeyField(
'app.models.user.User',
'id',
on_delete = fields.CASCADE
)
My question is if I am correctly implementing the foreign key in the user_id field, is it correct to write the path 'app.models.user.User' for the model name parameter? Do I have to import User in item.py to be able to do this?
Or, on the other hand, should I write in this parameter is 'user_db', which will be the name of the User model table? I'm tangled up with this.
Related
I have the following code that I cannot make it work.
I am new using Linq and Entity framework.
I attach the code sample, and also, and image with the error.
What I am trying to do, is a piece of code where I can add "Where"s dynamically.
Imports System.Linq
Private cntx As New attmanager_bdEntities()
Dim query = (From persona In cntx.tblperson
Select
ATT_TYPE = persona.att_type,
ATT_RECOG = persona.att_recog,
APELLIDO = persona.surname,
NOMBRE = persona.name,
PERSONA_ID = persona.id,
DNI = persona.identification,
DIRECCION = persona.address,
PIN = persona.att_pin,
TIPOASISTENCIA = persona.att_type,
EMAIL = persona.email,
EXTRA = persona.extra,
TELEFONO = persona.phone,
FECHANACIMIENTO = persona.birth,
SEXO = persona.sex,
DELETED = persona.deleted,
AREA_ID = persona.tblarea.id,
AREA = persona.tblarea.name,
CIUDAD = persona.tblcity.name,
CIUDAD_ID = persona.tblcity_id,
PROVINCIA = persona.tblcity.tblstate.name,
PAIS = persona.tblcity.tblstate.tblcountry.name
Where (DELETED = 0))
query = query.Where(Function(a) a.AREA_ID = 1)
'Here I should put another "Where"s
dbgrid_listado.DataSource = query.ToList()
Error translation:
Unexpected exception trying to load "personas"
Details:
Could not invoke the method because could not call a 'Public Function Where ..........
......
......
......
...... with those arguments.
The parameter 'predicate' of the argument could not be converted to VB$AnonymousDelegate_0(Of Object,Object)' into 'String'
Why not this?
Dim query = (From persona In cntx.tblperson
Where persona.DELETED = 0
Select persona)
Now your type is "persona" instead of an anonymous type of 21 random properties.
query = query.Where(Function(a) a.AREA_ID = 1)
Working with anonymous types is always tricky. Also, I always put the select last...
You could always list out the properties in an anonymous type like this:
Dim query = (From persona In cntx.tblperson
Where persona.DELETED = 0
Select New With {
ATT_TYPE = persona.att_type,
ATT_RECOG = persona.att_recog,
APELLIDO = persona.surname,
NOMBRE = persona.name,
PERSONA_ID = persona.id,
DNI = persona.identification,
DIRECCION = persona.address,
PIN = persona.att_pin,
TIPOASISTENCIA = persona.att_type,
EMAIL = persona.email,
EXTRA = persona.extra,
TELEFONO = persona.phone,
FECHANACIMIENTO = persona.birth,
SEXO = persona.sex,
DELETED = persona.deleted,
AREA_ID = persona.tblarea.id,
AREA = persona.tblarea.name,
CIUDAD = persona.tblcity.name,
CIUDAD_ID = persona.tblcity_id,
PROVINCIA = persona.tblcity.tblstate.name,
PAIS = persona.tblcity.tblstate.tblcountry.name
})
Maybe the where clause using the anon type is messing it up and using persona.DELETED = 0 would help?
I got it ....
I created a new project
I migrate all the resources (images for example) from the old project to this new one.
Opened the NuGet package manager, and installed EF6
Also installed MySQL.Data and MySQL EF6 provider.
I imported the forms, from the original project to the new one.
Now I can do what you guys suggested.
The Problem ??? .... The version on .Net framework, and the EF I was using.
I had t update everything.
These are MODELS:
class Event (models.Model):
status = models.CharField(max_length = 30, blank = True)
time = models.DateTimeField()
point = models.ForeignKey(Point)
person = models.ForeignKey(Person)
device = models.ForeignKey(Device)
organization = models.ForeignKey(Organization)
class Presence(models.Model):
point = models.ForeignKey(Point)
person = models.ForeignKey(Person)
date_from = models.DateTimeField()
date_to = models.DateTimeField()
This is SERIALIZERS:
class EventSerializer(serializers.ModelSerializer):
person = serializers.SlugRelatedField(queryset=Person.objects.all(), slug_field='card_tag')
class Meta:
model = Event
fields = ['id','time','point','person','device','organization']
this is API:
class EventAPI(viewsets.ModelViewSet):
serializer_class = cs.EventSerializer
This is URL:
url(r'^event/', api.EventAPI.as_view({'post':'create'}), name='event_create'),
so I want these:
after every creation of Event object, check it by %2 (getting number of objects by card_tag, which is in body of request), if it's number
of events %2 == 0 => create object of Presence, how can I do it ?
Thanks and sorry
You should be able to use the perform_create method, which by default looks something like:
def perform_create(self, serializer):
serializer.save()
Now you can override it and do pretty much anything you want.
def perform_create(self, serializer):
serializer.save()
if ..something.. % 2:
Presence.objects.create(...)
Consider the following models:
class Line(Document):
name = StringField()
class Root(Document):
name = StringField()
children = ListField(fields=ReferenceField('RootContent'))
class RootContent(Document):
meta = { 'allow_inheritance': True }
class Directory(RootContent):
name = StringField()
children = ListField(fields=ReferenceField('RootContent'))
class File(RootContent):
name = StringField()
children = ListField(fields=ReferenceField('Line'))
I need a serializer using django-rest-framework-mongoengine that may provide me with all roots having all directories and files, but not lines. I may set a fairly large value of "depth". How do I write a serializer that does it?
Finally I ended up doing something like the following:
from rest_framework_mongoengine import serializers as mongo_serializers
class ChildField(mongo_serializers.serializers.Serializer):
def to_native(self, value):
return self.parent.to_native(value)
class TreeSerializer(mongo_serializers.MongoEngineModelSerializer):
name = mongo_serializers.fields.SerializerMethodField(method_name='get_name')
children = ChildField(many=True)
class Meta:
model = Root
def get_name(self, obj):
"""Mainly in to nullify children of
object"""
if isinstance(obj, File):
obj.children = []
return obj.name
I am creating a custom module in Orchard. After I enable my module I would like to create a query programmatically.
I do that in my Migrations.cs file thanks to implementation of IDependency interface.
I am able to create the query but I do I programmatically set filters of that query?
var announcementsQuery = _contentManager.Create("Query");
announcementsQuery.As<TitlePart>().Title = "Announcements";
_contentManager.Publish(announcementsQuery);
I found out how to do this:
var announcementsQuery = _contentManager.Create("Query");
announcementsQuery.As<TitlePart>().Title = "Announcements";
announcementsQuery.As<QueryPart>().ContentItem.ContentType = "Announcement";
var filterGroupRecord = new FilterGroupRecord();
var filterRecord = new FilterRecord()
{
Category = "Content",
Type = "ContentTypes",
Description = "Announcement",
Position = 1,
State = "<Form><Description>Announcement</Description><ContentTypes>Announcement</ContentTypes></Form>"
};
filterGroupRecord.Filters.Insert(0, filterRecord);
announcementsQuery.As<QueryPart>().FilterGroups.Insert(0, filterGroupRecord);
Using a Groovy script with grails and want to do an update to a record in the database. I do the basic get the object from JSON and convert it to the Domain class and then do save() on it. From what I understand since I am new to Groovy and grails the save should update if the "id" is already there. But I don't get that, I get the standard SQL error of "Duplicate entry '1' for key 'PRIMARY'". How do I fix this?
def input = request.JSON
def instance = new Recorders(input)
instance.id = input.getAt("id")
instance.save()
and my domain is:
class Recorders {
Integer sdMode
Integer gsmMode
static mapping = {
id generator: "assigned"
}
static constraints = {
sdMode nullable: true
gsmMode nullable: true
}
}
Instead of doing a new Recorders(input), you probably ought to get it:
def input = request.JSON
def instance = Recorders.get(input.getAt('id'))
instance.properties = input
instance.save()
Edit
(From your comment) If it doesn't exist and you want to insert it:
def input = request.JSON
def id = input.getAt('id')
def instance = Recorders.get(id)
if(!instance) {
instance = new Recorders(id: id)
}
instance.properties = input
instance.save()
I don't use assigned id generators much, so I'm not sure if Grails will bind the id automatically (since it's expecting it to be assigned). If it does, you can probably remove the id: id from the Recorders() constructor.