21 – HOW TO ADD A FOREIGN FIELD IN DJANGO

Spread the love

1. Create a category model

class Category(models.Model):
	name = models.CharField(max_length=50, blank=True, null=True)
	def __str__(self):
		return self.name

2. Make migration and migrate

3. If you have any data in the existing Stock table, you will need to insert some data in the category table before proceeding

4. Update the Stock model. Change category from Charfield to ForeignKey

class Stock(models.Model):
	category = models.ForeignKey(Category, on_delete=models.CASCADE)

5. Chose a default ID for existing data in the Category table when prompted (Usually when adding a new field to an existing table that has data)


Spread the love

About the author

arbadjie

Hi, I'm Abdourahman Badjie, an aspiring developer with obsession for anything coding and networking. This blog is dedicated to helping people learn to develop web applications using django framework.

View all posts

27 Comments

  • Hi i really enjoyed your video and it was very helpful.
    but adding the foreign key ended up with giving a “FieldError”

    • def list_items(request):
      header = ‘List of listed items’
      form = StockSearchForm(request.POST or None)
      queryset = Stock.objects.all()
      context = {
      ‘header’: header,
      ‘queryset’: queryset,
      ‘form’: form,
      }
      if request.method == “POST”:
      queryset = Stock.objects.filter(category__name__icontains=form[‘category’].value(),
      item_name__icontains=form[‘item_name’].value())
      if form[‘export_to_CSV’].value() == True:
      response = HttpResponse(content_type=’text/csv’)
      response[‘Content-Disposition’] = ‘attachment;filename=”List of stock.csv”‘
      writer = csv.writer(response)
      writer.writerow([‘CATEGORY’, ‘ITEM_NAME’, ‘QUANTITY’])
      instance = queryset
      for stock in instance:
      writer.writerow([stock.category, stock.item_name, stock.quantity])
      return response
      context = {
      ‘header’: header,
      ‘queryset’: queryset,
      ‘form’: form,
      }
      return render(request, ‘list_items.html’, context)

  • hey
    i really liked your tutorials but i am now facing some errors .
    after adding the drop down choice list now we cannot add new categories and we have to move to admin panel to add it and after adding the foreign key we cannot add other items to the same categories and when we try to add it by making it as a string it says that category already exists
    please help me I really need to study this project.
    thank you

  • Hello. After this modification, ocorrurs this error:

    TypeError at /add_items/
    unsupported operand type(s) for +: ‘Category’ and ‘str’
    Request Method: POST
    Request URL: http://127.0.0.1:8000/add_items/
    Django Version: 2.2
    Exception Type: TypeError
    Exception Value:
    unsupported operand type(s) for +: ‘Category’ and ‘str’

      • Hi sir
        It’s very helpful for django beginners..
        With clear expectations and code notes..

        I’m student and started learning python django through your YouTube channel…

        I stuck in stock management system project..

        Video lecture 21 …

        I request you to please share me the complete code…

        So I will continue for learning…

        Thank you once again for helping students with free of cost…

  • Good evening Sir!
    please After changing my models to a ForeignKey and also after registering the Admin with the category, My list_Items start coming up with errors like

    OperationalError at /list_items/
    no such column: stockmgmt_stock.category_id
    Request Method: GET
    Request URL: http://127.0.0.1:8000/list_items/
    Django Version: 3.1.7
    Exception Type: OperationalError
    Exception Value:
    no such column: stockmgmt_stock.category_id
    Exception Location: C:\Users\Isibor Gamaliel\Desktop\DjangoApps\stockproject\env\lib\site-packages\django\db\backends\sqlite3\base.py, line 413, in execute
    Python Executable: C:\Users\Isibor Gamaliel\Desktop\DjangoApps\stockproject\env\Scripts\python.exe
    Python Version: 3.7.6
    Python Path:
    [‘C:\\Users\\Isibor Gamaliel\\Desktop\\DjangoApps\\stockproject\\src’,
    ‘C:\\Users\\Isibor Gamaliel\\anaconda3\\python37.zip’,
    ‘C:\\Users\\Isibor Gamaliel\\anaconda3\\DLLs’,
    ‘C:\\Users\\Isibor Gamaliel\\anaconda3\\lib’,
    ‘C:\\Users\\Isibor Gamaliel\\anaconda3’,
    ‘C:\\Users\\Isibor Gamaliel\\Desktop\\DjangoApps\\stockproject\\env’,
    ‘C:\\Users\\Isibor ‘
    ‘Gamaliel\\Desktop\\DjangoApps\\stockproject\\env\\lib\\site-packages’]
    Server time: Sun, 28 Feb 2021 22:30:31 +0000
    Error during template rendering
    In template C:\Users\Isibor Gamaliel\Desktop\DjangoApps\stockproject\src\stockmgmt\templates\list_items.html, error at line 64

    no such column: stockmgmt_stock.category_id
    54
    55
    56
    57 COUNT
    58 CATEGORY
    59 ITEM NAME
    60 QUANTITY IN STORE
    61 DELETE
    62
    63
    The error is indicating to this forloop instance in queryset
    64 {% for instance in queryset %}
    65
    66 {{forloop.counter}}
    67 {{instance.category}}
    68 {{instance.item_name}}
    69 {{instance.quantity}}
    70
    71
    72 {% endfor %}
    73
    74

    While powershell is also showing me this/

    return self.cursor.execute(sql, params)
    File “C:\Users\Isibor Gamaliel\Desktop\DjangoApps\stockproject\env\lib\site-packages\django\db\backends\sqlite3\base.py”, line 413, in execute
    return Database.Cursor.execute(self, query, params)
    django.db.utils.OperationalError: no such column: stockmgmt_stock.category_id.
    please what can i do?

  • Still Stuck on this page. Try remove last migrations. If Still not working Drop Tables. Then makemigrations. Still not working. Drop database. Just Delete it.
    Go for Migrations. All done. Everything working fine.

  • One more thing. Now you don’t need this piece of code

    category_choice = (
    (‘Furniture’, ‘Furniture’),
    (‘IT Equipment’, ‘IT Equipment’),
    (‘Phone’, ‘Phone’),
    (‘Electronics’, ‘Electronics’),
    )
    delete it or comment it for another project

  • Hey,
    Your videos are really helpful Abdourahman . I am following these as it is.
    In this tutorial I’m stuck and I’m not able to find the solution. The problem is that stockmgmt.catogery table is not creating in the database when i m running these commands. I’m a newbie so it might be a small issue. Please reply.

  • if i use “category = models.ForeignKey(Category,on_delete=models.CASCADE)” showing error

    53
    54
    55 COUNT
    56 CATEGORY
    57 ITEM NAME
    58 QUANTITY IN STORE
    59 Delete Items
    60
    61
    62 {% for instance in queryset %}
    63
    64 {{forloop.counter}}
    65 {{instance.category}}
    66 {{instance.item_name}}
    67 {{instance.quantity}}
    68 Delete
    69
    70 {% endfor %}
    71
    72

  • when i click home page and list_items,add_items showing his error

    Quit the server with CTRL-BREAK.
    [30/Jun/2021 04:07:31] “GET /list_items/ HTTP/1.1” 200 8084
    [30/Jun/2021 04:07:31] “GET /static/css/stylesheet.css HTTP/1.1” 304 0
    Not Found: /docs/4.4/dist/js/bootstrap.bundle.min.js
    [30/Jun/2021 04:07:31] “GET /docs/4.4/dist/js/bootstrap.bundle.min.js HTTP/1.1” 404 2735
    [30/Jun/2021 04:07:34] “GET /update_items/2/ HTTP/1.1” 200 3939
    Not Found: /docs/4.4/dist/js/bootstrap.bundle.min.js
    [30/Jun/2021 04:07:34] “GET /docs/4.4/dist/js/bootstrap.bundle.min.js HTTP/1.1” 404 2735
    [30/Jun/2021 04:07:48] “GET / HTTP/1.1” 200 3410

  • FieldError at /list_items/
    Related Field got invalid lookup: icontains
    Request Method: POST
    Request URL: http://127.0.0.1:8000/list_items/
    Django Version: 3.2.4
    Exception Type: FieldError
    Exception Value:
    Related Field got invalid lookup: icontains
    Exception Location: D:\python program\storestockproject\venv\lib\site-packages\django\db\models\sql\query.py, line 1182, in build_lookup
    Python Executable: D:\python program\storestockproject\venv\Scripts\python.exe
    Python Version: 3.9.2
    Python Path:
    [‘D:\\python program\\storestockproject\\venv’,
    ‘C:\\Users\\ASUS\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip’,
    ‘C:\\Users\\ASUS\\AppData\\Local\\Programs\\Python\\Python39\\DLLs’,
    ‘C:\\Users\\ASUS\\AppData\\Local\\Programs\\Python\\Python39\\lib’,
    ‘C:\\Users\\ASUS\\AppData\\Local\\Programs\\Python\\Python39’,
    ‘D:\\python program\\storestockproject\\venv’,
    ‘D:\\python program\\storestockproject\\venv\\lib\\site-packages’]
    Server time: Thu, 08 Jul 2021 09:06:04 +0000

  • Hey, I was following your tutorial no. 21 on Foreign Keys but unfortunately you didn’t illustrate how you went about your views.py to submit form data to the database with a FK. The video where you dealt with the views.py, the category had no FK. I’m working on a similar mini project with a Category as a FK but I’m stuck on how to submit form data to the database because of the category_id that is associated to my given category. Do you have a GitHub repo where I can find the project so that I can follow up with the views.py?

    Alternatively you can contribute to my Stack overflow question here (https://stackoverflow.com/questions/68733392/django-null-value-in-column-category-id-of-relation-apis-api-violates-not-n)

    Thank you and keep up the good work.

Leave a Reply to Muhammad Cancel reply

Your email address will not be published. Required fields are marked *