Learning Django - models.py ForeignKey or ManyToManyField or else?

103 views Asked by At

Trying to get some Django skills. I would like to have a class with one field being multiplied. So I can have more then one connected to my main class with an option of being active or not (for future needs).
So my subclass would look something like this:

class Subclass(models.Model):

  STATUS=(
  ('A', Active),
  ('U', Unactive)
  )
  status = modelsCharField(max_length=1, choices=STATUS)
  name = models.CharField(some options)

On main class I would like to call it as a reference but if I go for :

field=models.ManyToManyField(Subclass)

It is represented as a second table and for each entity I have to chose from all the entities of it. So if I have 2k entities in subclass I have to scroll true all of them to find my connection (in default admin page for instance)

I do not want that. All I need is 2 out of 2k entities that are connected and displayed in admin. And later on anly those with status Active would be displayed on the page itself.

So I figured I shall try a ForeignKey relation:

field=models.ForeignKey(Subclass, on_delegate=models.CASCADE)

This gives me errors about missing default values during migration though. Any help would be welcome, since I am a bit stuck right now.

1

There are 1 answers

0
Jan Mejor On BEST ANSWER

Big thanks to #AMG. I did as you sugested and now it works. In my models.py

class Person(models.Model):
name = models.CharField(max_length=200, default="Name")
phone = models.CharField(max_length=12, default="+22123456789")
...
class Adress(models.Model):
...
person = models.ForeignKey(Person, on_delete=models.CASCADE)
...

And my admin.py

from django.contrib import admin
from .models import Adress
from .models import Person

class AdressInline(admin.TabularInline):
model = Adress

class PersonAdmin(admin.ModelAdmin):
inlines = [
AdressInline    
]

admin.site.register(Person, PersonAdmin)

This lets me to add a Person object and add an adress for it on a same place. All I have to do now i formating the lists.