Tags down


Django model constraint - Sum of all rows for a user less than a constant

By : Canowyrms
Date : September 14 2020, 06:00 PM
it helps some times AFAIK you can't do that only with CheckConstraints but I think that you could enclose your model's save() method inside a transaction and do the check by yourself there. If the check fails simply raise an exception
code :
class Book(models.Model):
    user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    name = models.CharField(max_length=50)
    price = models.DecimalField(max_digits=6, decimal_places=2)

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        price_sum = Book.objects.filter(user=self.user).aggregate(price_sum=Sum('price'))['price_sum']  # You probably need some more code to handle corner cases
        if price_sum > 1000:
            raise PriceException()  # Made up exception. This will provoke a rollback

Share : facebook icon twitter icon

Django/SQLite User model UNIQUE constraint failed

By : Stephen G
Date : March 29 2020, 07:55 AM
around this issue Setting relation as user = models.OneToOneField(User) means that there can be the only one Change per User.
Change it to:
code :
user = models.ForeignKey(User)

Django UNIQUE constraint failed with OneToOneField while migrate in Django User Model

By : Allen Clineff
Date : March 29 2020, 07:55 AM
it fixes the issue You should change the relation with Blog model, as one Person can write more than 1 blog, hence its a 1-M relation. So in Blog model you should define a ForeignKey to Person model.
code :
person = models.ForeignKey(

After extending User profile to include a Profile model, Django throws UNIQUE Constraint Failed error

By : Yuri
Date : March 29 2020, 07:55 AM
Hope this helps I extended the User model to include a profile with the following code: , I changed the LeaveHistory model from:
code :
user = models.OneToOneField(User, on_delete=models.CASCADE) 
user = models.ForeignKey(User, on_delete=models.CASCADE) 

FOREIGN KEY constraint failed in django admin panel when creating/editing/deleting a user. (Using custom user model.)

By : Skip
Date : March 29 2020, 07:55 AM
To fix the issue you can do I asked around and the code should work in older versions of django. Sadly it won't work in django 2.0 or above. If anyone wants an alternative I found this to be perfect for my project, explanation is simple as well.

Django not saving the Custom User as the foreign key in another model: NOT NULL constraint failed

By : user3592982
Date : March 29 2020, 07:55 AM
With these it helps The error is raised because your Post model requires a mandatory user and your PostForm does not provide this. If you want to add the current user and do not want to add this field to your form you need to add the User before finally saving your model. You could do the following
code :
# Your other code

if form.is_valid():
    post = fom.save(commit=False)
    post.user = request.user

# more code
Related Posts Related Posts :
  • Why is this merge sort implementation not giving the correct answer?
  • Applying Filtering to a list which Removes Items
  • Delete substring between delimiters in python
  • Can ImageMagick be packaged with python program? How to do it?
  • Failing to import module named 'version' because izip_longest
  • UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte error in python while reading
  • How to apply multiple masks to a dataframe at the same time?
  • Printing longest subsequence of letters using Python
  • Find total from groupby.size() command
  • How to scrape a restricted webpage using Python
  • Converting text file into json in a specific format ( python )
  • Compare multiple images based on pixel values
  • Accessing a nested class from another nested dataclass
  • Print only even number using lambda and map functions
  • Parsing XML: Python ElementTree, find elements and its parent elements without other elements in same parent
  • Taking a list and printing all of the indexes of the elements that aren't equal to 0
  • UnboundLocalError: local variable 'di' referenced before assignment
  • How to convert JSON string with "" (instead of ") to JSON in Python
  • Equivalent of `const` reference to private class members in Python
  • Can't import tensorflow.keras in VS Code
  • How to uniquely copy values in dictionary, in list of dictionaries?
  • Outlier prediction with categorical data in Pythons Scikit-Learn lib
  • Django - Create related object on first call
  • How to use Hashlib to MD5 hash a number?
  • Flask-Toastr installation
  • How to validate a class attribute in python?
  • how to trim the dataframe using ranks in python and reshape them in a new dataframe
  • How do I sort the a list, ascending, by the date?
  • How to add a constant column with maximum value in a pyspark dataframe without grouping by
  • How to plot data in background of multiple subplots in matplotlib
  • Why is the dictionary i created out of another dictionary using a for loop smaller?
  • How to display image stored in Google Cloud bucket
  • How to check when BigQuery query result returns zero records?
  • How to fix `ResolvePackageNotFound` error when creating Conda environment?
  • Splitting a sentence where lower case and upper case are joint
  • Feature comparison between npm, pip, pipenv and poetry package managers
  • How to run a bash script through pycharm?
  • Can Python language be the fastest language in future?
  • How can I find rows in a pandas dataframe where value of col1 for row_x == value of col2 for row_y?
  • python black and white image detection
  • Split dataframe by rows and generate list of dataframes in python
  • Getting an error when trying to use the <= operator for two variables
  • Given a overlayed image (A^B) and one original image (A), how to calculate the other original image (B)
  • Remove "." and "\" from a string
  • How do I make this function able to use a numpy array as an argument and return an array in python?
  • Best way (performance-wise) to iterate over a dictionary
  • Execution time difference with and without a generator in Python3
  • Cannot use numpy with Spark
  • Why this is not working? ploting split outputs with matplotlib
  • Itertools without repetition and order
  • What is the difference between spacy.lang.en and load('en')?
  • How to get Twitter bio information with Tweepy
  • Permutations with repetitions?
  • How to make python ignore an object for garbage collection?
  • How to convert Lambda from Octave to Python
  • What does "model.trainable = False" mean in Keras?
  • Looking to return all possible rolls of two dice. The return value is a list which contains tuples
  • Looping through two arrays and adding the collection of each into new array without dups
  • Pandas dataframe average for each row conditional on dates
  • How to read a particular field from json data?
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk