I am having hard time to understand how to make field value unique while using Django MongoDB.my models.py has a model:
class Projects(models.Model):
projectName =models.CharField(max_length = 100,unique=True)
projectManager = EmbeddedModelField('Users')
Here i want whenever a new project instance is added it should have unique projectName.But this code is not working out as it allows adding same value for projectName and doesn't give me error.I read its possible to make field value Unique by using indexes in pymongo but how do I do it in Django MongoDB.
Answer to my own question is I had to add unique=True for model field before doing syncdb.Thanks to culebron.Its working now
Related
I don't understand well, how does django's autofield work... If I will run two app instances using gunicorn, will it be possible that my models get same autofield id?
I have a model Message and I want to check it's instance's id, but I want to be absolutly sure, that the ids are unique and are going by adding order.
The ids are unique for the specific model regardless of if it's within the same app or difference app. The id fields are sequential and increments by 1. Even if you delete an object, Django will not replace that ID.
There is no need to add the ID field when creating the model as Django takes care of that by itself.
If you want the id to be a unique set of character (for example- instead of the first object id being 1, you want it to be a unique number such as 12345678-1234-5678-1234-567812345678), you can use UUID (Universally Unique Identifier). In that case add the following field within your Message model-
Before running the below you would need to remove all migrations of the Message app and older records which still uses the id field.
class Message(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
in Django 1.10 -
I want to create multiple objects by importing - I'm uploading a file with data and creating objects with the given data. Before creating them I want to validate fields to make sure as much as I can that creation will pass successfully and collect as much data as I can about invalidate fields. For example, to find out whether a char field is too long.
I can use 'if' statement for each field but it's not robust.
I thought of using the model Serializer. The problem is that there are models to create that uses other models that also should be created. So when trying to validate the model that depends on the other one - it fails since it's not existed yet.
For example:
class FirstModel(BaseModel):
title = models.CharField(max_length=200)
identifier = models.CharField(max_length=15)
class SecondModel(BaseModel):
identifier = models.CharField(max_length=15)
firstModel = models.ForeignKey(FirstModel, related_name='first_model')
I think that my question is actually -
How can I validate only part of a model fields before creating it on DB?
Im working on a data migrations which needs to change a Foreign key to a different model and alter all the existing instances foreign keys to the new Model pk. I think this can be achieved with data migrations on Django. My question is:
¿How can I access previous versions of my models in order to perform the data migration?
I would like to do something like this:
MyPreviousModel = previousModels.MyModel
ModelAfterMigration = afterMigrations.MyModel
all_previous = MyPreviousModel.objects.all()
for element in all_previous:
element.previous_fk = new_foreignKey
ModelAfterMigrations.create(element)
Use the versioned app registry to get the model, rather than an import statement.
def my_migration(apps, schema_editor):
MyModel = apps.get_model("my_app", "MyModel")
The first argument passed to your migration worker function is an app registry that has the historical versions of all your models loaded into it to match where in your history the migration sits.
I have to add dynamic fields at run time in my django application,but I don't know the proper way how to add new fields at run time.
I want to add the code which will generate the dynamic field and will update database too. I am using postgresql database. please help if anyone can.
My "model.py" is simply like this:
class Student(models.Model):
name=models.CharField(max_length=100)
school=models.CharField(max_length=100)
created_at=models.DateField(auto_now_add=True)
is_active=models.BooleanField(default=False)
def __str__(self):
return self.name
Django is not made for dynamic models, as relational databases are not. A model change at runtime will create a ton of problems.
You have to simulate it, by...
clever use of related models
storing values in a large field, e.g. JSON as text
having a generic model that stores the data as key, value; e.g. a table with PK, a FK, key, value as columns.
You should try the first option and only if that does not work out try the other two.
I have two models and want to set a relation to them.
class ModelA(models.Model):
id = models.IntegerField(primary_key=True) # DB => PK, AI, NN
name = models.CharField(max_length=50)
...
class ModelB(models.Model):
modelA = models.OneToOneField("ModelA", primary_key=True)
description = models.CharField(max_length=255)
...
So I have a relationship between the two models. Is it possible to add a member to ModelA which stores the relation to ModelB without saving this relation to the database?
I would call it a dynamically created relation or something. Any hints oder suggestions how to let both models know each other?
I think it would be benefiting if the relation on one model can be done dynamically. Otherwise I'll get some trouble storing the models because one of the IDs won't be stored if I save one of the models.
I want to have the relation on both models so I can easily use the models as inline in django-admin.
regards
The reverse relation in Django is created by default.
To get the ModelA you will use:
ModelA.objects.filter(modelb__pk = 1)
You will find more details here:
https://docs.djangoproject.com/en/dev/topics/db/queries/
Django ORM will save ModelA first, then ModelB, in order to maintain data integrity in the DB.
Django can try saving multiple items in one transaction, and this way, if you cancel it, nothing will be saved, but this is possible in shell or in Python code. Over HTTP you can't maintain a transaction over several queries so far.
If you need to show model A as inline of model B, you need a custom admin interface, not new fields/models. I can't tell how to write custom admin widgets. I did do a similar thing with custom editor views & templates & Javascript. I stored the unsaved models in request.session.