Django电影和导演关系。电影未附加到导演。

huangapple go评论62阅读模式
英文:

Django movie and director relation. Movie is not attached to the director

问题

class Movie(models.Model):
name = models.CharField(max_length=100)
category = models.CharField(max_length=100)
imdb = models.DecimalField(max_digits=2, decimal_places=1)
director = models.ForeignKey('Director', on_delete=models.DO_NOTHING)

class Director(models.Model):
name = models.CharField(max_length=150)
movies = models.ManyToManyField(Movie, related_name='movies', blank=True)

I am creating a new movie using django-admin page. For instance; django-admin creating movie

However, the movie is not automatically added to the director.
Director

I also want a movie to belong to only one director.
How can I do these? I will be very glad if you can help me. Thanks in advance.

英文:

I'm making a model, consisting of a movie and a director. When I create a movie, I want the movie to be automatically owned by the director I selected but it's not working.


class Movie(models.Model):
    name = models.CharField(max_length=100)
    category = models.CharField(max_length=100)
    imdb = models.DecimalField(max_digits=2, decimal_places=1)     
    director = models.ForeignKey('Director', on_delete=models.DO_NOTHING)

    class Meta:
        verbose_name_plural = 'Movies'

    def __str__(self):
        return self.name


class Director(models.Model):
    name = models.CharField(max_length=150)
    movies = models.ManyToManyField(Movie, related_name='movies', blank=True)

    class Meta:
        verbose_name_plural = 'Directors'

    def __str__(self):
        return self.name
    

I am creating a new movie using django-admin page. for instance;django-admin creating movie

However the movie is not automatically added to the director.
Director

I also want a movie to belong to only one director.
How can I do these. I will be very glad if you can help me. Thanks in advance

答案1

得分: 0

以下是翻译好的内容:

这已经是没有需要额外关系的情况了。确实,您可以这样定义:

class Movie(models.Model):
    name = models.CharField(max_length=100)
    category = models.CharField(max_length=100)
    imdb = models.DecimalField(max_digits=2, decimal_places=1)
    director = models.ForeignKey(
        'Director', on_delete=models.DO_NOTHING, related_name='movies'
    )

    class Meta:
        verbose_name_plural = 'Movies'

    def __str__(self):
        return self.name


class Director(models.Model):
    name = models.CharField(max_length=150)

    class Meta:
        verbose_name_plural = 'Directors'

    def __str__(self):
        return self.name

如果您将导演 D1 分配给电影 M1,您可以使用以下方式查询该导演的电影:

D1.movies.all()

在模型管理中,您还可以通过 inline 方式显示电影,例如使用 TabularInline

from django.contrib import admin

class MovieInline(admin.TabularInline):
    model = Movie

@admin.register(Director)
class DirectorAdmin(admin.ModelAdmin):
    # ...
    inlines = [
        MovieInline,
    ]
英文:

That's already the case without any need for an extra relation. Indeed, you define this as:

<pre><code>class Movie(models.Model):
name = models.CharField(max_length=100)
category = models.CharField(max_length=100)
imdb = models.DecimalField(max_digits=2, decimal_places=1)
director = models.ForeignKey(
'Director', on_delete=models.DO_NOTHING, <b>related_name='movies'</b>
)

class Meta:
    verbose_name_plural = &#39;Movies&#39;

def __str__(self):
    return self.name

class Director(models.Model):
name = models.CharField(max_length=150)

class Meta:
    verbose_name_plural = &#39;Directors&#39;

def __str__(self):
    return self.name&lt;/code&gt;&lt;/pre&gt;

If you then assign a director <code>D<sub>1</sub></code> to a move <code>M<sub>1</sub></code>, you can query the movies of the director with:

<pre><code>D<sub>1</sub><b>.movies</b>.all()</code></pre>

In the modeladmin you can also display the movies when editing a Director through an inline, for example a TabularInline&nbsp;<sup>[Django-doc]</sup>:

<pre><code>from django.contrib import admin

class <b>MovieInline</b>(admin.TabularInline):
model = Movie

@admin.register(Director)
class DirectorAdmin(admin.ModelAdmin):
# &hellip;
inlines = [
<b>MovieInline</b>,
]</code></pre>

答案2

得分: 0

我按照你说的做了。我创建了一个新的电影Django电影和导演关系。电影未附加到导演。

但是它没有附加在这里,以列表的方式命名为movies Django电影和导演关系。电影未附加到导演。

以下是我的代码:
serializers.py

class MovieSerializer(serializers.ModelSerializer):

    class Meta:
        model = Movie
        fields = '__all__'
        read_only_fields = ['movie_id']


class DirectorSerializer(serializers.ModelSerializer):

    class Meta:
        model = Director
        fields = '__all__'

views.py

class DirectorListCreateAPIView(generics.ListCreateAPIView):
    queryset = Director.objects.all().order_by('id')
    serializer_class = serializers.DirectorSerializer
    permission_classes = [permissions.IsAuthenticated]
    authentication_classes = [authentication.BasicAuthentication]

    def get_queryset(self):
        queryset = Director.objects.all()
        name = self.request.query_params.get('name', None)
        if name is not None:
            queryset = queryset.filter(name=name)
        return queryset

class MovieListAPIView(generics.ListCreateAPIView):
    queryset = Movie.objects.all()
    serializer_class = serializers.MovieSerializer
    permission_classes = [permissions.IsAuthenticated]
    authentication_classes = [authentication.BasicAuthentication]
    filter_backends = [django_filters.DjangoFilterBackend, filters.OrderingFilter, filters.SearchFilter]
    filterset_fields = ['category', 'director']
    search_fields = ['category__name', 'director__name', 'name',]
    ordering_fields = ['production_year', 'imdb', 'duration']
英文:

I did as you said. I created a new movieDjango电影和导演关系。电影未附加到导演。

But It is not attached here as a list named movies Django电影和导演关系。电影未附加到导演。

Here are my codes:
serializers.py

class MovieSerializer(serializers.ModelSerializer):

    class Meta:
        model = Movie
        fields = &#39;__all__&#39;
        read_only_fields = [&#39;movie_id&#39;]


class DirectorSerializer(serializers.ModelSerializer):

    class Meta:
        model = Director
        fields = &#39;__all__&#39;

views.py

class DirectorListCreateAPIView(generics.ListCreateAPIView):
    queryset = Director.objects.all().order_by(&#39;id&#39;)
    serializer_class = serializers.DirectorSerializer
    permission_classes = [permissions.IsAuthenticated]
    authentication_classes = [authentication.BasicAuthentication]

    def get_queryset(self):
        queryset = Director.objects.all()
        name = self.request.query_params.get(&#39;name&#39;, None)
        if name is not None:
            queryset = queryset.filter(name=name)
        return queryset


class MovieListAPIView(generics.ListCreateAPIView):
    queryset = Movie.objects.all()
    serializer_class = serializers.MovieSerializer
    permission_classes = [permissions.IsAuthenticated]
    authentication_classes = [authentication.BasicAuthentication]
    filter_backends = [django_filters.DjangoFilterBackend, filters.OrderingFilter, filters.SearchFilter]
    filterset_fields = [&#39;category&#39;, &#39;director&#39;]
    search_fields = [&#39;category__name&#39;, &#39;director__name&#39;, &#39;name&#39;,]
    ordering_fields = [&#39;production_year&#39;, &#39;imdb&#39;, &#39;duration&#39;]

huangapple
  • 本文由 发表于 2023年4月4日 04:18:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75923457.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定