I am getting IntegrityError in Django - django-rest-framework

null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (1, 10000, 11200, null).
this is my models.py
id =models.CharField(max_length=6, primary_key = True, editable=False, unique=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
I was trying to return a Json Response

insert null = True in your id model, this will correct the integrity error.

You said you were trying to return a JSON response; was this saved in some way or another?
This error indicates that nothing is passed to the user field on save. Hence, you need to give the user field a user instance before saving. Can we see what you are trying to do in order to know how to fix the problem?

Related

How store null in database using vue and laravel?

I have Vue project with Laravel API, and also I have a column named expired_date: date it is nullable
this is the response after I dd the data from the network console:
The problem is when I store the data I just found the expired_date store value 0000-00-00
My code of store:
$data = $request->except('image');
if (!$request->expired_date) {
$data['expired_date'] = null;
}
Post::create($data);
The issue is that an empty string '' is being saved instead of null, resulting in 0000-00-00 values saved to the field. In this case it's because the ConvertEmptyStringsToNull middleware included with the framework was mistakenly commented out and disabled, so the solution is to re-enable that middleware.
Other common causes are forgetting to make the field nullable in the database, or having an incorrect default value.
To explicitly set a field to null without using the ConvertEmptyStringsToNull middleware, it is possible to use a mutator similar to this inside of the model:
public function setExpiredDateAttribute($date) {
$this->attributes['expired_date'] = empty($date) ? null : Carbon::parse($date);
}

drf-spectacular: how to show the primary key in examples section of Swagger

I'm trying to show the primary key in the examples section of Swagger, I'm using drf-spectacular and my code looks like:
Serializers.py
class SerializerExample(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('id','name')
Views.py
class BooksBulkUpdate(APIView):
#extend_schema(
request=SerializerExample(many=True),
responses={200:''},
)
def put(self, request, format=None):
with transaction.atomic():
for data in request.data:
book = Book.objects.get(pk=data['id'])
serializer = SerializerExample(book, data=data, partial=True)
if serializer.is_valid():
serializer.save()
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
return Response()
Only the name field is showing:
The only solution that I found was using an inline serializer which is not the ideal solution because if I update my book serializer I'd have to remember to update also this inline serializer. I wonder if there is a better way of doing this.
AFAIK swagger shows input request schema.
For example, you want to add new person and your model is
class Person(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=30)
So you allowed to set only name parameter
Even if you post
{
"id": "someUUID",
"name": "NAME",
}
id will be ignored and Django create it automatically by own logic (because it is read only)
But you can set id field writeable:
class SerializerExample(serializers.ModelSerializer):
id = serializers.UUIDField(write_only=True)
name = serializers.CharField(write_only=True)
class Meta:
model = Person
fields = ('id','name')
write_only=True means that field will be active when you saving new data and receiving id from request json.
In opposite read_only=True will print id field at response (if you trying get data) but ignore it when you saving new data.
So you try to describe API for data adding, and of course that is not allow to set id field in request json.
Not sure if this theory applicable to your case, but hope that will be helpful.

DRF : CreateAPIView - UNIQUE constraint failed

I am using Django Rest Framework with React for the front.
I want to post Note linked to a ForeignKey User.
models.Note
class Note(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
content = models.TextField(blank=True, default='')
serializers.NoteSerializer
class NoteSerializer(serializers.ModelSerializer):
user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all())
class Meta:
model = Note
fields = ('user', 'content')
When I post {user: 1, content: "test"}, I get the following error message:
UNIQUE constraint failed: app_note.user_id
How can I link the new Note to an existing user, posting the user.id?
I think my current code is trying to create a new User Instance...
You are using OneToOneField in Note model. That means a user can have only one note.
use ForeignKey instead to have many notes for single user.

django rest-framework add fields to ModelSerializer

I have the following serializer:
class AMXModXAdminsSerializer(mixins.GetCSConfigMixin, serializers.ModelSerializer):
admin = serializers.CharField(label='Admin', max_length=35, required=True, write_only=True)
password = serializers.CharField(label='Password', max_length=35, required=False, write_only=True)
access_flags = serializers.MultipleChoiceField(choices=ACCESS_FLAGS_OPTIONS, required=True, write_only=True)
account_flags = serializers.MultipleChoiceField(choices=ACCOUNT_FLAGS_OPTIONS, required=True, write_only=True)
class Meta:
model = CS16Server
fields = ('name', 'amxadmins', 'admin', 'password', 'access_flags', 'account_flags')
read_only_fields = ('name', 'amxadmins',)
When I try to access the url it complains:
Got AttributeError when attempting to get a value for field `admin` on serializer `AMXModXAdminsSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `CS16Server` instance.
Original exception text was: 'CS16Server' object has no attribute 'admin'.
If I add write_only to each field, the error will go away.
The thing is that I have a similar serializer, for the same model, with fields which do not belong to the model and it works perfectly without adding "write_only=True" to each field.
Any idea why one would work and another one no ?
What do u mean "when i access" ? post get put patch ?
Error says:
'CS16Server' object has no attribute 'admin'.
Does it ? if not , where do u intend to write it to ?
If model does not have admin field (as mentioned in error ) you need something like this:
class AMXModXAdminsSerializer(mixins.GetCSConfigMixin, serializers.ModelSerializer):
admin= serializers.SerializerMethodField()
fields ...
...
def get_admin(self, obj):
do somthing with self (contains the request) or the obj you're working on
return theOUTcome
If you set required=False it will not complain anymore because it will not try to get those fields values from db.

Eloquent Relation not returning errors or result

The following code does not return any error:
$exchange = Exchange::findOrFail(16);
dd($exchange->values);
The Exchange model has the following relation:
return $this->belongsTo(ExchangeValue::class, 'value', 'exchange_id');
The database schema is:
exchanges (id, type, title, description)
exchange_values (id, exchange_id, value)
Of course I've specified the database table in the ExchangeValue model because it doesn't follow the Laravel convention.
I have a record in the database with exchange_id 16 and it's returning null, without a query error or something.
What could be the issue?

Resources