Forienkey to same table

12 views
Skip to first unread message

Mohsen Pahlevanzadeh

unread,
Mar 29, 2020, 10:45:11 PM3/29/20
to django...@googlegroups.com
I have table A with my following fields:
1. id (PK)
2. fname (text)
3. name (text)
4. A_id (integer)

I have problem with 4th field, Because it has to refrenced to id
field. I can't implement it into Django.

How can I write model class for above table in models.py ?

--mohsen

Stephen J. Butler

unread,
Mar 30, 2020, 1:06:18 AM3/30/20
to django...@googlegroups.com
Instead of using the model class, or string name of the model class, use the string value 'self'.


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAJFFGZKZLQDNMA%2BzSUFKvUX8c0eMe%2B7do73cV1RyZTO1q-A3gg%40mail.gmail.com.

Metehan Gülaç

unread,
Mar 30, 2020, 5:15:43 AM3/30/20
to Django users
first of all, you can remove the 1. id (pK) line. django already create this field for you in background. I think you want to reference id field of A table to himself; it is known as recursive relationship. Speaking the which, you can use:

models.ForeignKey('self', on_delete=models.CASCADE)


30 Mart 2020 Pazartesi 05:45:11 UTC+3 tarihinde Mohsen Pahlevanzadeh yazdı:

Motaz Hejaze

unread,
Mar 30, 2020, 5:24:54 AM3/30/20
to Django users
What are the usages lf such a technique ??

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages