Creating a Django model with unique values for each user - django-models

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)

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

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?

Retrieve data from two tables with many to many relationship in Django?

I want to retrieve a data which has user id 1 from the table called file. The user and file table and many to many relationship. I want to show the file related to that user.
class GalaxyUser(models.Model):
id = models.IntegerField(primary_key=True)
create_time = models.DateTimeField(null=True, blank=True)
update_time = models.DateTimeField(null=True, blank=True)
email = models.CharField(max_length=765)
password = models.CharField(max_length=120)
external = models.IntegerField(null=True, blank=True)
deleted = models.IntegerField(null=True, blank=True)
purged = models.IntegerField(null=True, blank=True)
username = models.CharField(max_length=765, blank=True)
form_values_id = models.IntegerField(null=True, blank=True)
disk_usage = models.DecimalField(null=True, max_digits=16, decimal_places=0, blank=True)
class Meta:
db_table = u'galaxy_user'
class File(models.Model):
users = models.ManyToManyField(GalaxyUser)
file_name = models.CharField(max_length=100)
type = models.CharField(max_length=10)
source = models.CharField(max_length=100)
start_date = models.TextField()
end_date = models.TextField()
duration = models.TextField()
size = models.TextField()
flag = models.TextField()
If the user is logged in as user, I get the user_id let's say it's 1. Now, I want to retrieve the file name related to user 1 only. How can I do that?
File.objects.filter(users=GalaxyUser.objects.get(id=1))
You can use File.objects.filter(users__id__exact=1). Refer here.
user = GalaxyUser.objects.get(id=1)
files = user.file_set.all()
See more about ManyToMany lookups here

google datastore many to one references

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?

Resources