google datastore many to one references - google-app-engine

So i have two model classes:
class Dog(db.model):
dogName = StringProperty()
dogBreed = StringProperty()
class Cat(db.model):
catName = StringProperty()
catBreed = StringProperty()
and then i have a third model class to hold all the pictures
class Images(db.model):
imageReference = ReferenceProperty(*Animal*, collection_name = 'allImages')
imageURL = StringProperty()
Animal is either a Dog or a Cat. Obviously this does not compile.
Now my question is: Is there a way I can put Cat pictures in with Dog pictures? Or do I need to create more models like this:
class DogImages(db.model):
imageReference = ReferenceProperty(Dog, collection_name = 'allImages')
imageURL = StringProperty()
class CatImages(db.model):
imageReference = ReferenceProperty(Cat, collection_name = 'allImages')
imageURL = StringProperty()

You could use PolyModel:
class Animal(polymodel.PolyModel):
name = db.StringProperty()
breed = db.StringProperty()
class Dog(Animal):
pass
class Cat(Animal):
pass
Now you can have a ReferenceProperty that references Animals, and either Dogs or Cats will be permitted.
However, you don't have any properties that are specific to each type of animal - why not just have a regular Animal model, add a property indicating what species it is, and skip the separate models entirely?

Related

An error occurs when tries to add a model in django-admin. (many-to-many relations)

I want to connect with Product model and productcategory model with manytomany relation. When I write it like this.
class Product(models.Model):
id = models.CharField(primary_key=True, default=generateUUID(), max_length=36, unique=True, editable=False)
category = models.ManyToManyField('ProductCategory')
creatorid = models.ForeignKey('User', models.DO_NOTHING, db_column='creatorId', related_name='creator') # Field name made lowercase.
createdat = models.DateTimeField(db_column='createdAt', default=timezone.now) # Field name made lowercase.
updatedat = models.DateTimeField(db_column='updatedAt') # Field name made lowercase.
status = models.TextField(choices=PRODUCT_STATUS.choices) # This field type is a guess.
class Meta:
managed = False
db_table = 'product'
class ProductCategory(models.Model):
id = models.CharField(primary_key=True, default=generateUUID(), max_length=36, unique=True, editable=False)
name = models.TextField()
rootcategory = models.TextField(choices=PRODUCT_ROOT_CATEGORY.choices, blank=True, null=True, db_column='rootCategory') # Field name made lowercase. This field type is a guess.
icon = models.TextField()
class Meta:
managed = False
db_table = 'product_category'
When I try to add a product model in admin, the following error occurs. What's the problem?
Error ScreenShot

Django model keep field unchanged during update

My model is:
class Customer(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
created_by = models.EmailField(max_length=254, blank=True)
first_name = models.CharField(max_length=100, blank=False)
last_name = models.CharField(max_length=100, blank=False)
email = models.EmailField(max_length=254, blank=True)
phone = models.CharField(max_length=14, blank=False)
I would like created_at and created_by to stay unchanged upon update of the object. created_at works that way because of auto_now_add=True but I can't find a similar option for other model fields. Any ideas?
A simple solution with serializers is to override the update() function and refrain from updating the created_at and created_by fields.
For example in, lets say, serilalizers.py:
class CustomerSerializer(serializers.Serializer):
first_name = serializers.CharField(max_length=100)
last_name = serializers.CharField(max_length=100)
email = serializers.EmailField(max_length=254)
phone = serializers.CharField(max_length=14)
# Other functions like create() ...
def update(self, instance, validated_data):
instance.first_name = validated_data.get('first_name', instance.first_name)
instance.last_name = validated_data.get('last_name', instance.last_name)
instance.email = validated_data.get('email', instance.email)
instance.phone = validated_data.get('phone', instance.phone)
instance.save()
return instance

Creating a Django model with unique values for each user

I would like to create a site that helps users to remember meaning of certain words.
class Word(models.Model):
word = models.CharField(max_length=30, unique=True)
meaning = models.CharField(max_length=200)
memory_strength = models.FloatField()
user = models.ForeignKey(User)
I want each user to have individual (unique) value of memory_strength for every item of Word, while values of word and meaning would be the same for each and every user. How can I achieve that?
class Word(models.Model):
word = models.CharField(max_length=30, unique=True)
meaning = models.CharField(max_length=200)
class Memory(models.Model):
memory_strength = models.FloatField()
user = models.ForeignKey(User)
word = models.ForeignKey(Word)

Why is my write quota reached with a simple admin bulk remove?

This weird case happened twice already in the last 2 days.
I used Datastore Admin to remove all entities, no more than 100, to later reā€“upload db using remote_api_shell but after the request the Datastore Write Operations reached the limit:
This is the first and the only operation I did since last 24h reset.
Also the error is reported in remote_api_shell when I try to put new entities.
Any advice welcome.
Edit:
Here the models, nothing huge...
class Brand(BaseModel):
'''
Brand class
`Marca` in Etax db
'''
name = db.StringProperty()
abbr = db.StringProperty()
def __repr__(self):
return ('<Brand {0} instance at {1}>'
.format(self.abbr.encode('utf-8'), hex(id(self))))
class Model(BaseModel):
'''
Model class
`Gamma` in Etax db
'''
name = db.StringProperty()
code = db.IntegerProperty()
brand = db.ReferenceProperty(Brand, collection_name='models')
def __repr__(self):
return ('<Model {0} instance at {1}>'
.format(self.code, hex(id(self))))
class TrimLevel(BaseModel):
'''
Trim Level class
`Modello` in Etax db
'''
name = db.StringProperty()
etax_code = db.IntegerProperty()
start_production_date = db.DateProperty()
end_production_date = db.DateProperty()
retail_buy_prices = db.ListProperty(int)
retail_sell_prices = db.ListProperty(int)
list_prices = db.ListProperty(int)
model = db.ReferenceProperty(Model, collection_name='trim_levels')
fuel_supply = db.StringProperty()
gear_shift = db.StringProperty()
gear_speeds = db.IntegerProperty()
doors = db.IntegerProperty()
seats = db.IntegerProperty()
kw = db.IntegerProperty()
def __repr__(self):
return ('<TrimLevel {0} instance at {1}>'
.format(self.etax_code, hex(id(self))))
If you look at billing docs, that a high-level delete takes several low-level write operations:
Entity Delete (per entity): 2 writes + 2 writes per indexed property value + 1 write per composite index value
So if 100 entity deletes used 50k write ops, it means that your every entity had 500 index entries.
This can happen when entity has large list properties or havs a compound index spanning multiple list properties (= exploding index)
Do you have any compound indexes defined? What properties does your entity have?

Appengine error object has no attribute '_key'

I have a GAE database entity that looks like this:
class Notification(db.Model):
alert = db.StringProperty()
type = db.StringProperty()
status = db.StringProperty(default="unread", choices=set(["unread", "read"]))
created = db.DateTimeProperty(auto_now_add=True)
modified = db.DateTimeProperty(auto_now=True)
entity = db.StringProperty()
record = db.ReferenceProperty(model.RecordModel)
actor = db.ReferenceProperty(model.Profile)
account = db.ReferenceProperty(model.Account)
... and I create an entity like so:
notify = model2.Notification(account=account)
notify.alert = message
notify.type = "reminder"
notify.actor = actor
notify.record = record
notify.put()
This call raises an error *'Notification' object has no attribute '_key'*
nquery = db.Query(model2.Notification).filter('account =', self.session.account).order('-created')
for n in nquery:
try:
_dict = {}
_dict['serverID'] = str(n.key()) #- raises error!
try:
nquery = Notification.all().filter('account =', self.session.account).order('-created')
I think I've figured it out! The "entity" property in my Notification class is causing some sort of naming conflict in python appengine. Changing the name removes the "error object has no attribute '_key'" error. Go figure!

Resources