[Answered ]-I'm having trouble deciding between using a foreign key, many-to-many field, or choicefield

1👍

What you have actually implemented here is a Many To Many relationship between Consoles and Video Games without using Django’s ManyToManyField. It does seem that a many to many relationship is what’s required here.

The Game model corresponds to a ‘through’ model in django speak. But your Game model does not have any additional fields so it can be dropped completely to end up with just two models.

class GameConsole(models.Model):
    name = models.CharField(
        max_length=8,
        default='PC'
    )

    # console_logo = models.ImageField()

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = 'game console'
        verbose_name_plural = 'game consoles'
        db_table = 'console'
        ordering = ['-name']


class VideoGame(models.Model):
    title = models.CharField(
        max_length=128,
        default='???'
    )
    consoles = models.ManyToManyField(Console)
    # game_cover = models.ImageField()
    # company_website = models.URLField()
    # date_published = models.DateField()

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = 'video game'
        verbose_name_plural = 'video games'
        db_table = 'games'
        ordering = ['-title']

Then it’s possible for you to use Admin Inlines to Games from Console change forms and vice verce

If you want to display many-to-many relations using an inline, you can
do so by defining an InlineModelAdmin object for the relationship:

class GameInline(admin.TabularInline):
     model = VideoGame
     exclude = ('consoles',)

class ConsoleInline(admin.TabularInline):
     model = Console

class GameConsoleAdmin(admin.ModelAdmin):
    list_display = ['name']
    inlines = [ GameInline]

class GameAdmin(admin.ModelAdmin):
    list_display = ['game', 'console']
    inlines = [ ConsoleInline, ]    

admin.site.register(GameConsole, GameConsoleAdmin)
admin.site.register(Game, GameAdmin)
👤e4c5

1👍

Each game must be on at least one console, but it might be available
on more.

So, ‘Hello’ might run on ‘PC’ and ‘Playstation 4’, and ‘World’ might run only ‘PC’? That makes two Game Consoles to one Game ‘Hello’, but two Games for one Game Console ‘PC’. That sounds like a many-to-many relationship to me.

Leave a comment