How to check if foreign key exists?

Hello

Here I have a model called Staff which has OneToOne relation with django User model and ForeignKey relation to the Organization model.Here while deleting the organization I want to check if the organization exists in Staff model or not .If it exists in Staff model then i don't want to delete but if it doesn't exists in other table then only I want to delete.

How can I do it ?

I got this error with below code:

Exception Type: TypeError
Exception Value:    
argument of type 'bool' is not iterable

models.py

class Organization(models.Model):
    name = models.CharField(max_length=255, unique=True)
    slug = AutoSlugField(unique_with='id', populate_from='name')
    logo = models.FileField(upload_to='logo', blank=True, null=True)

class Staff(models.Model):
    user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, related_name='staff')
    name = models.CharField(max_length=255, blank=True, null=True)
    organization = models.ForeignKey(Organization, on_delete=models.SET_NULL, blank=True, null=True,
                                     related_name='staff')

views.py

def delete_organization(request, pk):
    organization = get_object_or_404(Organization, pk=pk)
    if organization in organization.staff.all().exists():
        messages.error(request,"Sorry can't be deleted.")
        return redirect('organization:view_organizations')
# also tried
# if organization in get_user_model().objects.filter(staff__organization=organizatin).exists():
    elif request.method == 'POST' and 'delete_single' in request.POST:
        organization.delete()
        messages.success(request, '{} deleted.'.format(organization.name))
        return redirect('organization:view_organizations')
Willem Van Onsem

The check should be:

def delete_organization(request, pk):
    organization = get_object_or_404(Organization, pk=pk)
    if organization.staff.exists():
        messages.error(request, "Sorry can't be deleted.")
        return redirect('organization:view_organizations')
    # ...

You can however optimize the above, by doing proper filtering in the get_object_or_404 already:

def delete_organization(request, pk):
    organization = get_object_or_404(Organization, pk=pk, is_staff__isnull=True)
    # ...

This will then raise a 404 in case the organization does not exist, or the organization exists, but has still some staff.

Based on the logic you wrote, you want to prevent that you can delete an organization if there is still staff. You can set such logic in the model layer as well, by using models.PROTECT as on_delete handler:

class Staff(models.Model):
    user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, related_name='staff')
    name = models.CharField(max_length=255, blank=True, null=True)
    organization = models.ForeignKey(Organization, on_delete=models.PROTECT, blank=True, related_name='staff')

Now Django will help you enforce that you do not, by accident, remove an Organization where there is still related staff, this makes it more safe.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

how to check if a property exists in a foreign key model?

how to check if foreign key exists in other table before adding a record

FluentMigrator - Check if Foreign Key exists before deleting it

How to check if a array key exists?

How to check the key is exists in collection or not

How to check if a json key exists?

How To Check If A Key in **kwargs Exists?

How To Check If A Key in **kwargs Exists?

How to check if an appSettings key exists?

How to check if a key exists in Partial?

SQL: How to check if foreign key was really changed

How to create check constraint with foreign key reference

how to check if key exists before adding in to dictionary

Java : How to check if a key is exists in a Hashmap

How to check if a key exists in Firebase Database?

How to check the key exists in the event lambda function

How can I check if a key exists in a dictionary?

How to check if JSON key exists or not in ruby

How to check if key exists in array of object

How to check for specific object key and update if exists

How to check if a key exists in a Ruby hash?

How to check if a given string key exists in Enum

How to check for a particular key exists in json string or not

How to check if key exists in multidimensional dictionary?

How To Check If A Combination Of Foreign Keys Exists Multiple Times

Django - Check if a non-foreign-key integer field exists as a Primary Key to another Model?

How do I drop a foreign key if it exists in Ruby on Rails?

How to disallow creation of object if related foreign key doesn't exists?

PostgreSQL insert if foreign key exists

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  3. 3

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  4. 4

    pump.io port in URL

  5. 5

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    Do Idle Snowflake Connections Use Cloud Services Credits?

  9. 9

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  10. 10

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  11. 11

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  12. 12

    Generate random UUIDv4 with Elm

  13. 13

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  14. 14

    Is it possible to Redo commits removed by GitHub Desktop's Undo on a Mac?

  15. 15

    flutter: dropdown item programmatically unselect problem

  16. 16

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  17. 17

    EXCEL: Find sum of values in one column with criteria from other column

  18. 18

    Pandas - check if dataframe has negative value in any column

  19. 19

    How to use merge windows unallocated space into Ubuntu using GParted?

  20. 20

    Make a B+ Tree concurrent thread safe

  21. 21

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

HotTag

Archive