mongoengine inheritance django - django

I've tried with this example: http://mongoengine-odm.readthedocs.org/en/latest/tutorial.html?highlight=query%20document%20inheritance#posts
but not working for me.
I want to store data from weather api:
http://api.met.no/weatherapi/locationforecast/1.8/?lat=46.079001;lon=14.51860012
so i have models.py like this
import mongoengine
class Weather(mongoengine.Document):
created = mongoengine.DateTimeField
latitude = mongoengine.DecimalField
longitude = mongoengine.DecimalField
model_name = mongoengine.StringField
class Precipitation(Weather):
dateFrom = mongoengine.DateTimeField(required=True)
dateTo = mongoengine.DateTimeField(required=True)
precipitation = mongoengine.DecimalField
symbol = mongoengine.IntField(min_value=1, max_value=23)
class State(Weather):
temperature = mongoengine.DecimalField
windDirection = mongoengine.StringField
windAngle = mongoengine.DecimalField
Trying to save data for example:
models.State.objects.create(temperature=17)
nothing is saved!
I know i'm missing arguments to constructor in fields definition but I don't really know how to implement it.

You need class instances eg:
import mongoengine
class Weather(mongoengine.Document):
created = mongoengine.DateTimeField()
latitude = mongoengine.DecimalField()
longitude = mongoengine.DecimalField()
model_name = mongoengine.StringField()
class Precipitation(Weather):
dateFrom = mongoengine.DateTimeField(required=True)
dateTo = mongoengine.DateTimeField(required=True)
precipitation = mongoengine.DecimalField
symbol = mongoengine.IntField(min_value=1, max_value=23)
class State(Weather):
temperature = mongoengine.DecimalField()
windDirection = mongoengine.StringField()
windAngle = mongoengine.DecimalField()

Related

Trying to change IntegerProperty to FloatProperty of existing AppEngine DataStore. Getting error Indexed value must be at most 1500 bytes

BEFORE :
class Person(ndb.Model):
name = ndb.StringProperty()
age = ndb.StringProperty()
other_details = ndb.StructuredProperty(OtherDetails, 'othrdtl')
class OtherDetails(ndb.Model):
success = ndb.StringProperty()
qr_code = ndb.TextProperty()
AFTER:
class Person(ndb.Expando):
pass
rows_to_be_updated = []
for person in Person.all():
person.age = int(person.age)
rows_to_be_updated.append(person)
if len(rows_to_be_updated)>0:
ndb.put_multi_async(rows_to_be_updated)
#"When the above line is executed i am getting error"
Very AFTER:
class Person(db.Model):
name = db.StringProperty()
age = db.IntegerProperty()
other_details = ndb.StructuredProperty(OtherDetails, 'othrdtl')
As per the datastore document, the TextProperty is unindexed by default. What is the reason for the error? I have tried making explicit Indexed=False (ndb.TextProperty(indexed= False)) but didn't work.
Instead of trying to go through an expando model, you might consider using a different name in your database than in your model.
E.g. after
class Person(ndb.Model):
name = ndb.StringProperty()
string_age = ndb.StringProperty('age')
age = ndb.IntegerProperty('int_age')
other_details = ndb.StructuredProperty(OtherDetails, 'othrdtl')
Then you could use a hook to ensure that Person.age is always set, e.g.
class Person(ndb.Model):
#classmethod
def _post_get_hook(cls, key, future):
p = future.get_result()
if p and not p.age:
p.age = int(p.string_age)

How can I save my object in an other table?

I have this code :
entryA = myTable1.objects.all().first()
entryB = copy.deepcopy(entryA)
But the problem is I would want to save entryB but if I do entryB.save() I will have a new entry in myTable1 whereas I want to have a new entry in myTable2 which contains the same fields.
Could you help me please ?
Thank you
Here is my model :
class myTable1(models.Model):
number = models.BooleanField(default=True)
date = models.DateField(default=None)
class myTable2(models.Model):
number = models.BooleanField(default=True)
date = models.DateField(default=None)
You'll need to copy the properties of one object to another object and then use the create method to create a new instance.
class myTable1(models.Model):
number = models.BooleanField(default=True)
date = models.DateField(default=None)
class myTable2(models.Model):
number = models.BooleanField(default=True)
date = models.DateField(default=None)
entryA = myTable1.objects.all().first()
entryB = myTable2.objects.create(number=entryA.number, date=entryA.date)
Or if you want myTable2 to have unique data, you can do:
entryA = myTable1.objects.all().first()
entryB, created = myTable2.objects.get_or_create(number=entryA.number, date=entryA.date)

Saving Django Form With Foreign Key Reference

I have a form which references three models and I want to save the items to each model. One of the models has foreign key references to the other models and I want to save them too.
My models look like:
class Address(models.Model):
housenumber = models.CharField(max_length=20,default='',blank=True)
street = models.CharField(max_length=80,default='',blank=True)
town = models.CharField(max_length=80,default='',blank=True)
county = models.CharField(max_length=60,default='',blank=True)
country = models.CharField(max_length=20,default='',blank=True)
postcode = models.CharField(max_length=10,default='',blank=True)
class GeoLocation(models.Model):
longitude = models.FloatField(default=-4.2576300)
latitude = models.FloatField(default=55.8651500)
class Location(models.Model):
locationname = models.CharField(max_length=80,default='',blank=True)
address = models.ForeignKey(Address, on_delete=models.CASCADE)
geolocation = models.ForeignKey(GeoLocation, on_delete=models.CASCADE, default='')
My views looks like:
if locationform.is_valid() and addressform.is_valid() and geolocationform.is_valid():
locationform.save(commit=False)
new_address = addressform.save()
new_geolocation = geolocationform.save()
locationform.address = new_address
locationform.geolocation = new_geolocation
locationform.save()
This will give me an error that states "NOT NULL constraint failed: location_location.address_id".
Can anyone help? I am new to Django so find this stuff hard.
Thanks Eduardo I managed to get it working with the following code, almost the same as yours:
if locationform.is_valid() and addressform.is_valid() and geolocationform.is_valid():
new_location = locationform.save(commit=False)
new_address = addressform.save()
new_geolocation = geolocationform.save()
Location.objects.create(
locationname= new_location.locationname,
address=new_address,
geolocation=new_geolocation)
One solution could be:
if locationform.is_valid() and addressform.is_valid() and geolocationform.is_valid():
new_address = addressform.save()
new_geolocation = geolocationform.save()
locationform.address = new_address
locationform.geolocation = new_geolocation
Location.objects.create(
locationname=locationform.data.get('locationname', " ",
address=new_address,
geolocation=new_geolocation)

Django Model inheritance and access children based on category

I want to get the parent class values with each child values? How can I identify child objects to fetch?
I have the Django model structure like this.
class Category(models.Model):
name = models.CharField(max_length=80)
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
category = models.ForeignKey('Category')
class PizzaRestaurant(Place):
serves_hot_dogs = models.BooleanField(default=False)
serves_pizza = models.BooleanField(default=False)
class PastaRestaurant(Place):
extra = models.CharField(max_length=80)
When we do operation we may save the object like below. And it saved into the db as i expected. two entry in the Place table and each entry in each child object table.
a = Category()
a.name = "pasta"
b = Category()
b.name = "pizza"
a.save()
b.save()
x = PastaRestaurant()
x.address = "Pasta Address"
x.name = "Pastamonia"
x.extra = "some extra"
x.category = a
y = PizzaRestaurant()
y.address = "Pizza Address"
y.name = "Dominos"
y.serves_hot_dogs = 1
y.serves_pizza = 0
y.category = b
x.save()
y.save()
Now I need to access the like this
p = Place.objects.get(id=1)
How can I know, which objects/attributes belongs to the place objects?
So when I fetch the place with common attributes and should be able get the corresponding child objects values also.
Or any other model design work for my need?
If you want to access the child model's attributes you need to fetch it as that model, i e PizzaRestaurant or PastaRestaurant, otherwise you will only get a Place object.
If you need to get all Places regardless of subclass take a look at InheritanceManager from django-model-utils. Using this you can implement overloaded operations to perform subclass-specific actions.
django-polymorphic does this beautifully, improving the abilities to work with model inheritance like so:
from polymorphic.models import PolymorphicModel
class Place(PolymorphicModel):
...
class PizzaRestaurant(Place):
...
class PastaRestaurant(Place:
...
>>> some_place = Place.objects.create(name="Walmart")
>>> some_pizza_place = PizzaRestaurant.objects.create(name="Slice King", address="101 Main St., Bismarck, ND", category = Category.objects.first(),serves_pizza=True)
>>> some_pizza_place.instance_of(PizzaPlace)
True
>>> PizzaRestaurant.objects.all()
queryset<['Slice King',]>
>>> Place.objects.all()
queryset<['Walmart', 'Slice King',]>

how to compare related Sum with a value itself

class Investor(Model):
name = CharField(max_length=16)
class Project(Model):
plan_finance = IntegerField()
class ProjectProcess(Model):
project = OneToOneField('Project')
investors = ManyToManyField('Investor')
class InvestShip(Model):
project = ForeignKey('Project')
investor = ForeignKey('Investor')
invest_amount = IntegerField()
How to find the Project which have already finished being financed , in other words, the money received from investors' > plan_finance.
You can use annotation on the related set and then filter on it.
from django.db.models import Sum
Project.objects.annotate(invested_sum=Sum('investship_set__invest_amount')).filter(invested_sum__gte=plan_finance)