Django - validate model before saving to DB - python

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?

Related

Practical way to render form widget for a OneToMany relation in django. (Need to nest fields of multiple models in one auto generated form)

Let's say we have the following pseudo database structure:
models.py
class Order(models.Model):
...
class OrderItem(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
...
So each Order may contain one or more OrderItems.
By default, if I render the default form for these models, we will end up with two separate forms, where the user will have to create the Order first in one form, and then navigate to another form for OrderItem to start creating OrderItems for that Order.
Unless I create my own custom form from scratch (which is not integrated with any models) and then write the code to connect it with data models in the server-side. However, this is a very common use case so there has to be a way to handle such a scenario without having to rebuild so much from scratch.
Django already has a ManyToManyField which allows us to handle a similar kind of operation where what the user sees in the auto-generated form is simple, yet it involves interaction with multiple data models. How come there's no way to handle such form representation of data without having to do so much from scratch?
For example, in Django Rest Framework we can use Nested Relationships to define one model serializer as a field of another model serializer. But for Django models, I couldn't find any documentation for anything similar.

Is there a way to have multiple instances of a model embedded into a single model field in Django?

I know the foreign key concept,Djongo Array field , however is there an alternative?
The issue with the foreign key concept is that I would need to make multiple hits to the database and the issue with Array field is the lack of information and the errors emerging without a known solution.
What I would like to do basically is in fact add multiple instances of a model say comments to a single field in another model but I would like to embed it rather than creating a new table for comments which I tried using an abstract model however it did not work out.
I would like to know any alternative solution.
You can use foreign keys, and to avoid making separate query for every related record you can extract them all at once using prefetch_related - https://docs.djangoproject.com/en/3.1/ref/models/querysets/#prefetch-related :
Returns a QuerySet that will automatically retrieve, in a single batch, related objects for each of the specified lookups.
Code example:
# models.py
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
class Comment(models.Model):
post = models.ForeignKey(Post, models.CASCADE)
text = models.TextField()
# Somewhere else, fetch posts together with related comments:
# It will take 2 requests in total
# - one to fetch posts, another to fetch all related comments
for post in Post.objects.all().prefetch_related('comment_set'):
print([c.text for c in post.comment_set.all()])

Django Model Unique Constraint Exception

I have a django model that has a unique together constraint, but I need a specific instance to be able to be repeated over and over. Is this possible?
name = models.ForeignKey(name)
time = models.BigIntegerField()
class Meta:
unique_together = ("name", "time",)
I'm trying to get time=0 and for the same user multiple times. However, in every other instance it time needs to be unique.
A unique_together field is validated on database level (see documentation). It is therefore not possible to make exceptions.
A solution could be to set time = null instead of time = 0.
Your database backend needs to support unique constraint that allows empty values (see this post). This is supported by most major DBMS, but not all.
If you database does not support it you'll have to write a custom form validation.

python django one-to-one relations between two models

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.

Creating field value "unique" throughout the collection in Django MongoDB models?

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

Categories

Resources