How to create object of one Model after creating another Model's object using serialization and modelViewSet - serialization

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(...)

Related

Loading a dropdown content dynamically

I'm new in the Odoo world and now I'm stuck. I have this (Odoo v11.0):
Model: class Dog()
dog_name = fields.Char()
gps = fields.Many2One(Model Gps)
Model: class Gps()
serial = fields.Char()
I have a Gps list that is show in the Dog's form as a dropdown list, each time a Dog record is created only one Gps can be assigned to it, so the next time I create a Dog those assigned Gps must not appear in the dropdown list.
How to accomplish it?
Thanx in advance
Please add below method in class Gps.
#api.multi
def name_get(self):
if self._context.get('filter_gps'):
gps_records = self.env['Dog'].search([('gps','!=',False)]).mapped('gps')
new_self = self - gps_records
return super(Gps,new_self).name_get()
return super(Gps,self).name_get()
Add this method to Dog class:
#api.one
#api.onchange('gps')
def onchange_gps(self):
If not self.gps:
Res = {}
Ids = []
Dogs = self.env['dog'].search([])
Ids = [d.gps for d in dogs]
Res['Domain'] = {'gps' : [('id', 'not in', ids)]}
Return res

Django - id null - foreign key error

Error:
app_a.desc_id may not be NULL
I believe my problem is I'm not passing the id from formB to formA when I save. please please lead me to a solution for this problem.
Here's my view:
def form(request):
if request.method == 'GET':
formB = BForm()
formA = AForm()
return render(request,r'app/form.html',{'formA':formA,'formB':formB})
elif request.method == 'POST':
formA = AForm(request.POST)
formB = BForm(request.POST)
formB.save()
formA.save()
return HttpResponseRedirect('/log')
Here are my models:
# Descprition
class B(models.Model):
id = models.AutoField(primary_key=True)
description = models.CharField(max_length=50)
# Title
class A(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField('Name',max_length=20)
desc = models.ForeignKey(B)
and here is my form:
class BForm(forms.ModelForm):
class Meta:
model = B
fields = ['description']
class AForm(forms.ModelForm):
class Meta:
model = A
fields = ['name']
Your program has multiple errors but the main problem for this is because desc is a foreign key in class A that points to class B, and you don't have null=True on it, meaning you never want that field to be empty. In other words, each instance of A should have a foreign key desc.
If you just save() both forms, formA tries to save an instance of A, without having a value for desc field, hence the error. You should assign the instance that formB creates to the instance that formA creates:
new_b = formB.save()
new_a = formA.save(commit=False)
new_a.desc = new_b
new_a.save()
Other problems in your program including never called form.is_valid(), having redundant id fields(django would create one for you). I suggest you read django tutorial first before jumping into coding. It would save a lot of time like figuring out errors like this.

How can I make raw sql ManyToMany and Annotation in django?

class Post(models.Model):
user = models.ForeignKey(FBUser, related_name='posts')
group = models.ForeignKey(Group, related_name='posts')
class Comment(models.Model):
user = models.ForeignKey(FBUser, related_name='comments')
post = models.ForeignKey(Post, related_name='comments')
group = models.ForeignKey(Group, related_name='comments')
class Group(models.Model):
name = models.CharField(max_length=100)
I made this code, but this code is really slow to get result over 10 seconds.
_group.user_set.filter(posts__group=_group, comments__group=_group) \
.annotate(p_count=Count('posts', distinct=True), c_count=Count('comments', distinct=True))
How can I make this code to raw sql?

Serializer for mongo models excluding specific related class type

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

JSON Grail Groovy Update SQL

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.