【发布时间】:2022-01-01 11:29:21
【问题描述】:
我想从 REST API 获取用户名。我得到的是 ID,但不是用户名。这是我的serializer.py
class OfferSeriaLizer(serializers.ModelSerializer):
class Meta:
model = Offer
fields = ['id', 'offer_title', 'image', 'user', 'click', 'category']
这是我的模型
class Offer(models.Model):
Offer_STATUS = (
("ACTIVE", "ACTIVE"),
("PENDING APPROVAL", "PENDING APPROVAL"),
("REQUIRED MODIFICATION", "REQUIRED MODIFICATION"),
("DENIED", "DENIED"),
("PAUSED", "PAUSED"),
)
slug = models.SlugField(unique=True, null=True)
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
offer_title = models.CharField(max_length=240)
seo_title = models.CharField(max_length=60, null=True)
image = models.ImageField(upload_to='images/')
extra_images = models.ManyToManyField(ExtraImage, blank=True)
offer_video = models.FileField(upload_to="images/", blank=True, null=True)
document = models.FileField(upload_to="files/", null=True, blank=True)
service = models.ForeignKey(Services, on_delete=models.CASCADE, null=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, related_name="offers")
sub_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE, null=True, blank=True)
child_subcategory = models.ForeignKey(ChildSubcategory, on_delete=models.CASCADE, null=True, blank=True)
packages = models.ManyToManyField(Package, through='OfferManager')
description = models.TextField()
# offer_rating = models.FloatField(default=0)
is_popular = models.BooleanField(default=False, null=True)
pop_web = models.BooleanField(default=False, null=True, blank=True)
is_pro = models.BooleanField(default=False, null=True)
click = models.PositiveIntegerField(null=True, blank=True, default=0)
impressions = models.PositiveIntegerField(default=0, null=True, blank=True)
order_count = models.PositiveIntegerField(default=0, null=True, blank=True)
cancellation = models.PositiveIntegerField(default=0, null=True, blank=True)
offer_status = models.CharField(max_length=200, null=True, choices=Offer_STATUS, default="PENDING APPROVAL")
is_premium = models.BooleanField(default=False)
is_bronze = models.BooleanField(default=False, null=True)
bronze_created = models.DateTimeField(null=True, blank=True)
is_silver = models.BooleanField(default=False, null=True)
silver_created = models.DateTimeField(null=True, blank=True)
is_gold = models.BooleanField(default=False, null=True)
gold_created = models.DateTimeField(null=True, blank=True)
is_pending = models.BooleanField(null=True, blank=True, default=True)
created_at = models.DateTimeField(auto_now_add=True, null=True)
# From Admin Side
has_checked = models.BooleanField(default=False)
already_clicked = models.BooleanField(default=False)
# Pointing Sytem DB
points = models.PositiveIntegerField(null=True, default=0)
这是我的看法
class OfferApiView(APIView):
def get(self, request):
offers = Offer.objects.filter(offer_status="ACTIVE")
serializer = OfferSeriaLizer(offers, many=True)
return Response(serializer.data)
这是我的 API 服务代码
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import 'package:marketage_v2/models/offer_model.dart';
class OfferController with ChangeNotifier {
List<OfferModel> _offers = [];
Future<bool> getOffers() async {
var url = Uri.parse("https://marketage.io/api/offers/");
try {
http.Response response = await http.get(url);
var data = json.decode(response.body) as List;
List<OfferModel> temp = [];
for (var element in data) {
OfferModel offermodel = OfferModel.fromJson(element);
temp.add(offermodel);
}
_offers = temp;
notifyListeners();
return true;
} catch (e) {
return false;
}
}
List<OfferModel> get offers {
return [..._offers];
}
OfferModel offerDetails(id) {
return _offers.firstWhere((element) => element.id == id);
}
}
这是我的颤振模型
class OfferModel {
late int id;
late String offerTitle;
late String image;
late int category;
late int user;
late int click;
OfferModel(
{required this.id,
required this.offerTitle,
required this.image,
required this.category,
required this.user,
required this.click});
OfferModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
offerTitle = json['offer_title'];
image = json['image'];
category = json['category'];
user = json['user'];
click = json['click'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['offer_title'] = this.offerTitle;
data['image'] = this.image;
data['category'] = this.category;
data['user'] = this.user;
data['click'] = this.click;
return data;
}
}
这是我的设计代码
// ignore: import_of_legacy_library_into_null_safe
// ignore_for_file: avoid_unnecessary_containers, sized_box_for_whitespace
import 'package:carousel_pro/carousel_pro.dart';
import 'package:flutter/material.dart';
import 'package:marketage_v2/controllers/offer_controller.dart';
import 'package:marketage_v2/screens/basic.dart';
import 'package:marketage_v2/screens/premium.dart';
import 'package:marketage_v2/screens/standard.dart';
import 'package:marketage_v2/widgets/offer_card.dart';
import 'package:provider/provider.dart';
import 'package:smooth_star_rating/smooth_star_rating.dart';
class OfferDetails extends StatelessWidget {
static const routeName = "/offer-details";
const OfferDetails({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final id = ModalRoute.of(context)!.settings.arguments;
// final offer_details =
// Provider.of<OfferController>(context).offerDetails(id);
final offers = Provider.of<OfferController>(context).offerDetails(id);
final offer = Provider.of<OfferController>(context).offers;
return Scaffold(
backgroundColor: const Color(0xFFe6e6e6),
body: ListView(
children: [
Container(
height: 200,
width: double.infinity,
child: Card(
elevation: 2,
child: Carousel(
dotBgColor: Colors.transparent,
dotSize: 0.0,
autoplay: true,
animationDuration: const Duration(milliseconds: 2000),
images: [
Image.network("https://marketage.io/${offers.image}"),
],
),
),
),
Container(
height: 5,
),
Container(
height: 60,
width: double.infinity,
child: Card(
elevation: 2,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
children: [
Container(
child: Row(
children: [
// Container(
// padding: const EdgeInsets.only(top: 5, left: 10),
// child: CircleAvatar(
// radius: 20,
// backgroundColor: Color(0xFFe6e6e6),
// backgroundImage:
// Image.network("src"),
// ),
// ),
Container(
padding: const EdgeInsets.only(left: 10, top: 5),
child: Text(
"${offers.user}",
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
),
],
),
),
],
),
Container(
width: 197,
padding: const EdgeInsets.only(right: 10),
// color: Colors.amber,
alignment: Alignment.centerRight,
child: const Text(
"Lvl 2",
style: TextStyle(
fontSize: 17,
fontWeight: FontWeight.w500,
color: Colors.black54,
),
),
),
],
),
),
),
Container(
height: 5,
),
Container(
color: Colors.white,
height: 40,
child: const DefaultTabController(
length: 3,
child: TabBar(
indicatorColor: Color(0xFF0099ff),
labelColor: (Colors.black),
unselectedLabelColor: Color(0xff0099ff),
tabs: [
Tab(
child: Text(
'Basic',
style: TextStyle(
fontSize: 20,
),
),
),
Tab(
child: Text(
'Standard',
style: TextStyle(
fontSize: 20,
),
),
),
Tab(
child: Text(
'Premium',
style: TextStyle(
fontSize: 20,
),
),
),
],
),
),
),
// const TabBarView(
// children: [
// Basic(),
// Standard(),
// Premium(),
// ],
// ),
Container(
height: 5,
),
Container(
child: Card(
elevation: 2,
child: Column(
children: [
Container(
padding: const EdgeInsets.all(7),
alignment: Alignment.center,
child: const Text(
"I will design and develop fully customized website",
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
),
),
),
Container(
height: 1,
color: const Color(0xFFd9d9d9),
),
Container(
padding: const EdgeInsets.all(7),
child: const Text(
"I am a professional Senior Front End developer as a PSD2HTML expert with 5+ years of experience In my Five years of career, I have completed more than 300 projects in different languages and frameworks. I have a strong grip as a Front End developer on HTML5, CSS3, Bootstrap4, Jquery, Javascript, SASS, React. if you want to convert your (psd to html, xd to html, sketch to html, psd to wordpress, psd to react), then you are at the right places and we can discuss the work and continue.",
style: TextStyle(
fontSize: 18,
),
),
),
Container(
height: 15,
),
],
),
),
),
Container(
height: 5,
),
Container(
width: double.infinity,
child: Card(
elevation: 3,
child: Column(
children: [
Container(
padding: const EdgeInsets.only(top: 20),
// alignment: Alignment.center,
child: const Text(
"About This Seller",
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.w500,
),
),
),
Container(
height: 15,
),
Container(
child: const CircleAvatar(
radius: 50,
backgroundColor: Color(0xFFededed),
backgroundImage: AssetImage("images/tsunade.png"),
),
),
Container(
height: 15,
),
Container(
child: const Text(
"Sakib Ovi Chan",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
Container(
height: 15,
),
Container(
// padding: const EdgeInsets.fromLTRB(65, 0, 0, 0),
child: SmoothStarRating(
isReadOnly: false,
size: 40,
filledIconData: Icons.star,
halfFilledIconData: Icons.star_half,
defaultIconData: Icons.star_border,
starCount: 5,
allowHalfRating: true,
spacing: 1,
color: Colors.amber,
borderColor: const Color(0xFFff6666),
),
),
Container(
height: 15,
),
Container(
alignment: Alignment.center,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
minimumSize: const Size(250, 40),
// textStyle: const TextStyle(fontSize: 25),
primary: const Color(0xFF63b9eb),
onPrimary: const Color(0xFFffffff),
),
child: const Text(
"Contact Me",
style: TextStyle(
fontSize: 22,
// fontWeight: FontWeight.bold,
color: Color(0xFFffffff),
),
),
onPressed: () {},
),
),
Container(
height: 20,
),
Container(
padding: const EdgeInsets.only(left: 25, right: 25),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
child: const Text(
"From",
style: TextStyle(
fontSize: 20,
color: Colors.black54,
),
),
),
Container(
child: const Text(
"Member Since",
style: TextStyle(
fontSize: 20,
color: Colors.black54,
),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
child: const Text(
"Bangladesh",
style: TextStyle(
fontSize: 20,
color: Colors.black,
),
),
),
Container(
child: const Text(
"Mar.07, 2021",
style: TextStyle(
fontSize: 20,
color: Colors.black,
),
),
),
],
),
],
),
),
Container(
height: 10,
),
],
),
),
),
Container(
child: Card(
elevation: 3,
child: Column(
children: [
Container(
padding: const EdgeInsets.only(top: 15),
alignment: Alignment.center,
child: const Text(
"My Project",
style: TextStyle(
fontSize: 23,
fontWeight: FontWeight.bold,
),
),
),
Container(
height: 15,
),
Container(
alignment: Alignment.center,
child: Column(
children: [
Container(
child: const Text(
"gngbd.com",
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w500,
),
),
),
Container(
child: const Text(
"marketage.io",
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w500,
),
),
),
Container(
child: const Text(
"mustaqeem.com",
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w500,
),
),
),
Container(
child: const Text(
"urbandokan.com",
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w500,
),
),
),
Container(
child: const Text(
"flashoff.com",
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w500,
),
),
),
Container(
child: const Text(
"stackclone.com",
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w500,
),
),
),
Container(
child: const Text(
"bloggy.com",
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w500,
),
),
),
Container(
height: 10,
),
],
),
),
],
),
),
),
// const Expanded(
// child: TabBarView(
// children: [
// Basic(),
// Standard(),
// Premium(),
// ],
// ),
// ),
// const TabBarView(
// children: [
// Basic(),
// Standard(),
// Premium(),
// ],
// ),
Container(
height: 10,
),
],
),
);
}
}
这是我要显示用户名的地方
Container(
padding: const EdgeInsets.only(left: 10, top: 5),
child: Text(
"${offers.user}",
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
),
如何从该代码中获取用户名。我需要改进代码或 API 吗?我怎样才能得到我的用户名??
【问题讨论】:
标签: flutter http dart django-rest-framework