Skip to content

Mixins with M2M fields can't be reused. #5

@meric

Description

@meric
    from django.db import models
    from modelmixins import ModelMixin

    class Car(models.Model):
        model = models.CharField(max_length=200)
        color = models.CharField(max_length=200)

    class CarOwner(ModelMixin):
        cars = models.ManyToManyField(Car)

    class Person(models.Model, CarOwner):
        firstname = models.CharField(max_length=200)
        lastname = models.CharField(max_length=200)

    class Driver(models.Model, CarOwner):
        firstname = models.CharField(max_length=200)
        lastname = models.CharField(max_length=200)

Let's say you have code like this.

Trying to run it , you'll get an error:

    ERRORS:
    core.Person_cars: (fields.E336) The model is used as an intermediate model by 'core.Driver.cars', but it does not have a foreign key to 'Driver' or 'Car'.

Work around:

    from django.db import models
    from modelmixins import ModelMixin

    class Car(models.Model):
        model = models.CharField(max_length=200)
        color = models.CharField(max_length=200)

    def CarOwner():
        class CarOwner(ModelMixin):
            cars = models.ManyToManyField(Car)
        return CarOwner

    class Person(models.Model, CarOwner()):
        firstname = models.CharField(max_length=200)
        lastname = models.CharField(max_length=200)

    class Driver(models.Model, CarOwner()):
        firstname = models.CharField(max_length=200)
        lastname = models.CharField(max_length=200)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions